C Code Style & Best Practices
In this page:
Clean Indentation
Consistent indentation has zero effect on how the compiler interprets your code, but it has a huge effect on how quickly a human — including your future self — can visually parse nested blocks, matching braces, and control flow at a glance.
Example: Clean Indentation
#include <stdio.h>
int main() {
if (1) {
printf("Properly indented block");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Meaningful Variable Names
Choosing descriptive variable names like totalScore instead of x or ts costs almost nothing to type but saves real time later, since the name itself documents what the variable holds without requiring a comment. Short single-letter names are still fine for tight, conventional contexts like loop counters (i, j, k).
Example: Meaningful Variable Names
#include <stdio.h>
int main() {
int totalScore = 95;
printf("%d", totalScore);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Centralizing Constants
Scattering unexplained numeric literals like 86400 or 3.14159 directly inside your logic makes the code hard to understand and hard to change safely; giving each one a name via #define or a const variable turns a mystery number into self-documenting code and means you only have to update it in one place.
Example: Centralizing Constants
#include <stdio.h>
#define SECONDS_PER_DAY 86400
int main() {
printf("%d", SECONDS_PER_DAY);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Function Modularity
Keeping each function focused on a single, well-defined task makes it easier to test, easier to reuse elsewhere, and easier to reason about in isolation, whereas one enormous function that does five unrelated things becomes progressively harder to modify safely as it grows.
Example: Function Modularity
#include <stdio.h>
int square(int n) {
return n * n;
}
int main() {
printf("%d", square(4));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Avoiding Magic Numbers
A magic number is any unexplained literal value embedded directly in your code whose meaning isn't obvious from context, and replacing it with a named constant (like MAX_ATTEMPTS instead of a bare 3) makes the intent of that value clear to anyone reading the code later.
Example: Avoiding Magic Numbers
#include <stdio.h>
#define MAX_ATTEMPTS 3
int main() {
printf("%d", MAX_ATTEMPTS);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 20 topics to unlock
0/20 topics done
Complete these topics first:
- C typedef
- C Type Casting
- C Bit Fields
- C Variable Length Arrays
- C Command Line Arguments
- C Function Pointers
- C Callback Functions
- C Multidimensional Pointer
- C string.h Functions
- C stdlib.h Functions
- C math.h Functions
- C time.h Functions
- C ctype.h Functions
- C errno.h
- C assert.h
- C Error Handling
- C Debugging Techniques
- C Code Style & Best Practices
- C Common Mistakes
- C Interview Questions