Are global variables always initialized to zero in C?

#include <stdio.h> int a[100]; int main(){ printf("%d",a[5]); return 0; } 

Does the above code print "0" or a specific compiler? I use the gcc compiler and I got the output as "0".

+7
source share
6 answers

Yes, all members of a must be initialized to 0.

From section 3.5.7 of the C89 standard

If an object that has a static storage duration is not initialized explicitly, it is initialized implicitly, as if each member that has an arithmetic type was assigned 0, and each member having a pointer type was assigned a null pointer constant.

+20
source

"Global variables" are defined in the file area outside any function. All variables defined in the file area and all variables declared with the static have something called static storage duration. This means that they will be allocated in a separate part of the memory and will exist throughout the entire duration of the program.

This also means that they are guaranteed to be initialized to zero on any C compiler.

From the current C11 standard 6.7.9 / 10:

"... If an object that has a static or storage duration of threads is not initialized explicitly, then:

- if it has a pointer type, it is initialized with a null pointer;

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

In practice, this means that if you initialize your global variable with a given value, it will have that value and will be allocated in a memory segment, usually called .data . If you do not give it a value, it will be highlighted in another segment called .bss . Globals will never be allocated on the stack.

+7
source

Yes. Any global variable is initialized to the default value of this type. 0 is the default value and is automatically assigned to any type. If it is a pointer, 0 becomes NULL

Global variables get a place in the data segment, which is nullified.

It is not specific to the compiler, but defined in the C standard.

Therefore, it will always print 0.

+3
source

Scope objects declared without explicit initializers are initialized to 0 by default (and NULL for pointers).

Non-static objects in the block region declared without explicit initializers remain uninitialized.

+2
source

Is the globle variable always initialized to zero in C?

Yes, and He is defined in the standard C.

+1
source

This is not a specific compiler. The code will always print 0 .

0
source

All Articles