Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it guaranteed that global variables are always initialized to 0 with c99?

From 6.7.8.10 in the C99 standard:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules;

— if it is a union, the first named member is initialized (recursively) according to these rules.

Is a global variable of any type (array, structure, bitfield) always defined as a static storage?

like image 655
nowox Avatar asked Jan 04 '23 16:01

nowox


1 Answers

Is it guaranteed that global variables are always initialized to 0 with c99?

Yes and no

static void *g_v_ptr;  // initialized to a null pointer

C99 details a value, but not its representation. "it has pointer type, it is initialized to a null pointer" implies that the pointer has value of a null pointer. This may or may not be NULL. This may or may not be 0. A compiler may have many bit patterns that correspond to a null pointer. In any case, the g_v_ptr == NULL is true as well as g_v_ptr == 0, but the pointer may have a different bit representation than 0. Certainly a pattern of all zero bits is usually easy to implement and certainly the most likely implementation. Yet the spec is just squishy enough to allow for some non-zero bit pattern to be used.

A similar case can be made for floating point numbers.

In any case (IAC), the initialized value will equate to 0.

like image 194
chux - Reinstate Monica Avatar answered Jan 11 '23 00:01

chux - Reinstate Monica