Are global variables always initialized to zero in C?

34,449

Solution 1

Yes, all members of a are guaranteed to be initialised to 0.

From section 3.5.7 of the C89 standard

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

Solution 2

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

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

From the current C standard C11 6.7.9/10:

"... If an object that has static or thread 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;"

Practically, this means that if you initialize your global variable to a given value, it will have that value and it will be allocated in a memory segment usually referred to as .data. If you don't give it a value, it will be allocated in another segment called .bss. Globals will never be allocated on the stack.

Solution 3

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

Global variables get there space in the data segment which is zeroed out.

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

So it will always print 0.

Solution 4

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

Non-static objects at block scope declared without explicit initializers are left uninitialized.

Solution 5

Are the globle variable always initalized to zero in C?

Yes and It's defined in the C standard.

Share:
34,449
Alex
Author by

Alex

Updated on July 22, 2022

Comments

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

    Does the above code always print '0' or is it compiler specific? I'm using gcc compiler and I got the output as '0'.