#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'.
Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code.
There's no need to initialize them, as the C standard requires global, uninitialized variables to be implicitly initialized to zero or NULL (no matter whether they are static or exported).
In C language both the global and static variables must be initialized with constant values. This is because the values of these variables must be known before the execution starts. An error will be generated if the constant values are not provided for global and static variables.
Since globals and static structures have static storage duration, the answer is yes - they are zero initialized (pointers in the structure will be set to the NULL pointer value, which is usually zero bits, but strictly speaking doesn't need to be).
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.
"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.
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