Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the default value of int fields of a local struct variable?

Tags:

c

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?

like image 360
Jude Gao Avatar asked Feb 04 '18 03:02

Jude Gao


2 Answers

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.

like image 87
Jonathan Leffler Avatar answered Nov 14 '22 23:11

Jonathan Leffler


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
}
like image 43
abelenky Avatar answered Nov 14 '22 21:11

abelenky