← Back to C Course | Chapter 12: Advanced Topics | Lesson 18 of 20

C Code Style & Best Practices

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

c
#include <stdio.h>
int main() {
	if (1) {
		printf("Properly indented block");
	}
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int totalScore = 95;
	printf("%d", totalScore);
	return 0;
}

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

c
#include <stdio.h>
#define SECONDS_PER_DAY 86400
int main() {
	printf("%d", SECONDS_PER_DAY);
	return 0;
}

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

c
#include <stdio.h>
int square(int n) {
	return n * n;
}
int main() {
	printf("%d", square(4));
	return 0;
}

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

c
#include <stdio.h>
#define MAX_ATTEMPTS 3
int main() {
	printf("%d", MAX_ATTEMPTS);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.