Coding Guidelines for C Programming

Avoiding pitfalls and securing the code is necessary!!!

This is one of my long pending post. Good coding practice will avoid lot of errors, warnings, segmentation fault, and etc., It will also help other people to understand and reuse the code in future.

Commenting & Style


  • Comments need to be added for special case handling such as string manipulation, etc.,
  • Function Header Format according to project's process.
  • Avoid obvious comments. 
                // If string is mac address
                Eg : if (string == "mac-address")     
               The above style of commenting is not recommended.
  • Consistent Naming scheme.
  • File and directory organization. 

  Indentation & Space

  • Add space after comma in the printf statements. 
              printf("arg1 %d\n",<space>arg1); 
  • Space after the keyword switch.  
              switch<space>(num)

  • Limit the line length.



Code Grouping 


Error handling

  • Function should have return value. Use macro for return values other than 0 or 1. 
  • Check the return value to handle the success and failure cases.
  • Add the return value in the error log/prints. Be specific to let others(especially customers) know what is the error. Don't add the error log is understandable only by developers. 

Macros

  • Use macros for all arguments such as strings, integer and etc., which are passed as an arguments in a function call. Macro name should be reusable in the future.

Function 

  • Avoid Deep Nesting 

Unit-Testing 

  • If you add any code during system startup, verify it with different values. 
          Eg : Check the functions which will be executed during system startup.

Common Mistakes

  • Don't add your sprint-2 code in sprint-1. You will be asked so many questions, if you are not handle it properly with good design. 

Return

  • If integer variable is used as return value, keep maintain that instead of using magic numbers such as 0 & 1/-1.
  • Avoid multiple returns. 
  • For void functions, use just "return;".


                                                                                                  -- Will be updated 

Comments