What's the default value of int fields of a local struct variable? Will they be zeroed automatically? Or, will they be the same as any other local variables, filled with garbage values?
If the variable has automatic storage — a local variable — and is not explicitly initialized, its state is indefinite. That applies regardless of whether it is a simple variable (e.g. an int
) or complex (e.g. a structure or union).
The fields will not reliably be zeroed.
C11 §6.7.9 Initialization ¶10:
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.
Note that static
variables are automatically initialized to zero, including local static variables.
Consider this example:
typedef struct
{
int alpha;
char bravo;
float charlie;
} ThreeVarStruct_T; // Define a structure
int function(void) // Local Scope
{
ThreeVarStruct_T exampleA; // This will hold uninitialized "random" data
static ThreeVarStruct_T exampleB; // This is guaranteed to be initialized to zero
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With