C Coding Standard
If you writing a code it should be understand by anyone also. Generally developers follows the codding standards. Different different company are following different different coding standers as per they need. You can follow some standard structure for all your usage.
A C Coding Standard is a set of guidelines and best practices that define how C code should be written, formatted, and structured.
It ensures:
- Consistency → All developers write code in the same style.
- Readability → Code is easy to read and maintain.
- Portability → Works across compilers and platforms.
- Reliability & Safety → Reduces bugs and undefined behaviors.
- Compliance → For safety-critical domains (e.g., MISRA-C for automotive).
Common Rules in C Coding Standards
Naming Conventions
- Variables:
lower_case_with_underscores→engine_speed - Constants/Macros:
ALL_CAPS→MAX_BUFFER_SIZE - Functions:
verb_noun→init_timer(),read_sensor() - Files:
.cand.hwith meaningful names →adc_driver.c,adc_driver.h
Code Formatting
- Use consistent indentation (2 or 4 spaces).
- Place braces on new lines (K&R or Allman style, but consistent).
if (x > 0) { do_something(); } else { handle_error(); }
Comments
- Use
/* ... */for block comments. - Explain why, not just what.
- Function header comments should describe purpose, inputs, outputs:
/** * @brief Calculates factorial of a number. * @param n Input integer * @return Factorial of n */ int factorial(int n);
Functions
- Keep them small and modular (Single Responsibility Principle).
- Avoid deep nesting (max 3–4 levels).
- Always use function prototypes in header files.
Variables
- Initialize variables before use.
- Avoid global variables if possible (or mark them
static). - Use
constfor read-only data. - Prefer
enumor#defineinstead of magic numbers.
Pointers & Memory
- Check for NULL before dereferencing.
- Free allocated memory properly.
- Avoid unsafe functions (
gets(),strcpy()→ use safer alternatives likefgets(),strncpy()).
Control Structures
- Always use braces
{}even for single-lineif,for,while.if (flag) { count++; }
Error Handling
- Always check return values of functions (e.g.,
malloc(),fopen()). - Provide clear error messages or error codes.
Variable declaration
/*
* Variable Name : int <Variable_Name>.
* Variable scope : Local or global or static or volatile or bool.
* Variable type : int or char or .
* Variable Size : 4 bytes (0 to 65535).
* Description : This value is used to store the 4byte of Generated CRC32 value.
* Initialize value : 0(Need to initialize with 0).
Function Declaration
/****************************************************
* Function Name : <Function_name>
* Purpose : <Function Purpose>
* Parameters : <list f parameters if any>
* Returns : <Return_Type>
* Global Modified : <global_Modifier_List>
*****************************************************/