The C Language

initialization

When you move into a new room, you can either leave it exactly as the previous tenant left it — full of unknown clutter — or you can clear it and set it up the way you want from the very start. In C, when a variable is born it gets some memory, and that memory may hold whatever leftover bits were already there. Initialization is the act of giving a variable a known starting value at the moment it is created, so it is never holding garbage.

You initialize by writing an equals sign and a value as part of the declaration, as in 'int x = 5;'. For arrays and structs you use braces, as in 'int a[3] = {1, 2, 3};'. There is a crucial difference based on where the variable lives. A variable with automatic (local) storage that you do NOT initialize starts with an indeterminate value — reading it before assignment is undefined behavior. A variable with static or global storage that you do not initialize is automatically set to zero by the runtime startup. So the danger zone is uninitialized local variables.

Why this matters: reading an uninitialized variable is one of the most common and slippery bugs in C, because the program may appear to work by luck (the leftover bits happened to be reasonable) and then fail mysteriously on another machine or build. The safe habit is to initialize variables at declaration whenever you can. Tools like the compiler warning -Wuninitialized and the MemorySanitizer exist specifically to catch this.

int total = 0; /* initialized to a known value */ int counts[4] = {0}; /* all four elements set to 0 */ int stray; /* NOT initialized: holds garbage */ /* printf("%d", stray); would be undefined behavior */

total and counts start with known values; stray is a local left uninitialized, so reading it is undefined behavior.

Only static and global variables are auto-zeroed; uninitialized LOCAL (automatic) variables hold indeterminate bits, and reading them is undefined behavior — not merely a random number. Initialize at declaration whenever possible.

Also called
initializer起始設定初值設定