Translation


by Transposh

Posts Tagged ‘coding standards for C’

Coding Best Practices for C – Part – 1

Sunday, October 11th, 2009

“Hello world” is the first lesson in any language. We always always try to improve our coding knowledge.  But for a professional development we should follow good and generic standards for writing a code. With my experience in C,I understood the fact,that writing a code is not a great thing. But writing a error free code in small span of time and  which can be referred or enhanced by other developers without any confusion makes a perfect code. As I strongly believe, Today’s best solutions becomes tomorrows Best Practices. We need to learn form our mistake and others experience to become perfect.

With this perception I would like to share my experience to enrich your Coding experience.

Here is some standard for coding C that you can follow to get the best result, and can save your life from Reviewer’s comments.

If you have below goals in mind:

  • Code should be robust and error free.
  • Code should be easy to use and understand.
  • Code should be easy to maintain.

This is for you.

Naming Conventions

General:

  • Clear and informative names are one of the best tools for creating easily understandable code. The name of any identifier should   succinctly describe the purpose of that identifier.
  • Avoid abstract names (in a global context) that are likely to be reused by other parts of the system.

File Names:

  • Header(.h) files should have the same name as the .c for header files dedicated to the .c.
  • File names should be made up of a prefix, underscore, base name, period and suffix.  File names should be consistent with the area of the application being modified.  File names should represent the content or role of the file.
  • Header file names should have the extension “.h”.
  • C Implementation (source) file names should have the extension “.c”

Function Names:

  • Function names should reflect what they do or what they return.
  • Do NOT re-use names of functions from the standards libraries (such as printf or strlen).
  • Function names should normally be formed from two parts: an action (verb) and an object (noun) of the action. Exceptions are query functions where the second part is not a noun, but the name should form a “question”.
    eg. GetSystemTime() SetStringLength()

Variable Names:

  • Variable names should be descriptive of the variable’s functions.
  • Constant names should be in all CAPS, with multiple words separated by an underscore, e.g.  MAX_PAGERS.
  • Macros, with or without parameters, should also be in all CAPS.
  • Enumeration constants and global typedef names should be in all CAPS with individual words separated by underscores, e.g. DATA_VALID.