Declaring and initializing variables is a cornerstone of the C language with very strict and sometimes non-obvious rules. How and where you declare a variable can affect its initial value (concerning initialization) as well as its association with a memory object (concerning declaration and definition).
C dates back to times when memory optimization was a priority. Developers had to manually declare and initialize variables; otherwise, the program's behavior became unpredictable. In modern C compilers, even small deviations can lead to linker errors or implicit initialization with "garbage".
Common errors:
Code example:
#include <stdio.h> int global_var; // definition, auto-initialization = 0 static int static_global_var; // static file, auto-initialization = 0 extern int extern_var; // declaration, definition somewhere else void foo() { int local_var; // automatic, uninitialized -> garbage static int static_local_var; // static, auto-initialized to 0 }
Key points:
1. Are automatic variables (local without static and extern) automatically initialized to 0 by the compiler?
No, they contain garbage. Their value is undefined; using them before initialization is an error.
2. Can you define a variable with extern multiple times in different files?
No, there should be one definition, with the rest being declarations via extern; otherwise, the linker will issue "multiple definition" or "undefined symbol" errors.
3. What is the difference between a function declaration and its definition?
A declaration is just a prototype (without a body); a definition must include the function's body. For variables, a declaration via extern does not reserve memory, while both forms are allowed for functions.
A global variable int counter; is declared in two header files. The project linked with a "multiple definition" error.
Pros:
Cons:
In the header, extern int counter; is declared; definition int counter = 0; — only in one C file.
Pros:
Cons: