Lesson 50 of 50 ¡ c
Best Practices & Coding Style for C
Duration: 12 mins
Consistent style makes code readable and maintainable.
đ Recommended Style Guidelines
- Naming â
snake_casefor variables/functions,PascalCasefor types. - Brace placement â K&R or Allman â pick one and stick with it.
- Line length â keep under 80â100 characters.
- Header guards â
#ifndef MY_HEADER_H ⌠#endif. - Commenting â use
/** ... */for API docs; inline//for explanations. - Limit globals â prefer passing parameters.
- Always check return values of system calls.
- Prefer
size_tfor sizes/indices,intptr_tfor pointerâinteger casts. - Use
constwherever data wonât change. - Static analysis (
clangâtidy) and formatting (clangâformat -style=Google).
đ Example Header Guard & Naming
#ifndef UTILS_MATH_H
#define UTILS_MATH_H
/**
* Compute the greatest common divisor (Euclidean algorithm).
*/
int gcd(int a, int b);
#endif // UTILS_MATH_H
đŻ Checklist for Every Commit
clang-format -i *.c *.h- Run
clang-tidywith your project config. - Compile with
-Wall -Wextra -Werror(treat warnings as errors). - Ensure no memory leaks (
valgrind). - Add or update unit tests if new functionality was added.