Are global variables always initialized to zero in C? [duplicate]

£可爱£侵袭症+ 提交于 2020-01-09 07:15:11

问题


#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'.


回答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.




回答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.




回答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.




回答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.




回答5:


Are the globle variable always initalized to zero in C?

Yes and It's defined in the C standard.




回答6:


It is not compiler specific. The code will always print 0.



来源:https://stackoverflow.com/questions/16015656/are-global-variables-always-initialized-to-zero-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!