Coding Techniques
C Variables · Study material
Keep state private with file-scope static
Instead of a global that any file can change, keep the variable static in one file and offer small functions to use it. This is how C does encapsulation.
#include <stdio.h>
static int total = 0; /* private to this file: no other file can change it */
void add(int n) { total += n; }
int get_total(void) { return total; }
void reset(void) { total = 0; }
int main(void) {
add(5);
add(7);
printf("%d ", get_total());
reset();
add(3);
printf("%d\n", get_total());
return 0;
}
12 3
Share a global across files correctly
Define the variable once in a .c file, and put an extern declaration in the header that other files include.
/* config.h */
extern int max_users; /* declaration only */
/* config.c */
#include "config.h"
int max_users = 100; /* the single definition */
/* main.c */
#include "config.h"
void check(int n) { if (n > max_users) puts("too many users"); }Defining it in the header instead would create a definition in every file that includes it – a "multiple definition" link error.
Declare variables in the smallest scope
Declare a variable where it is first needed and give it a value at once. A small scope makes code easier to read, prevents accidental reuse, and lets the compiler warn about unused or uninitialised variables.
for (size_t i = 0; i < n; i++) { /* i exists only for the loop */
double scaled = a[i] * factor; /* scaled exists only for one pass */
total += scaled;
} Good variable habits
- Initialise every local at its declaration.
- Use descriptive names:
total_marks, nottm. - Prefer parameters and return values over globals.
- Make file-level helpers and data
static. - Use
constfor values that should not change. - Compile with
-Wall -Wextra -Wshadow.