What does printf print for an unitialized variable?

孤街浪徒 提交于 2020-01-07 08:55:08

问题


What should the code print? 0 or any garbage value or will it depend on the compiler?

#include <stdio.h>
int a;
int main() 
{ 
   printf("%d\n",a);
   return 0;
}

回答1:


the answer is 0. Global variables are initialized to zero.




回答2:


I would say your code might output anything or simply anything can happen because your code invokes Undefined Behaviour as per C99.

You don't have a prototype for printf in scope.

J.2 Undefined behavior

— For call to a function without a function prototype in scope where the function is defined with a function prototype, either the prototype ends with an ellipsis or the types of the arguments after promotion are not compatible with the types of the parameters (6.5.2.2).

If the question is about initialization of global variables then a would be initialized to 0 because it has static storage duration.




回答3:


I found on C99 standard, Section 6.7.8.10, Initialization:

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.

Section 6.2.4.3 defines:

An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

In other words, globals are initialized as 0. Automatic variables (i.e. non-static locals) are not automatically initialized.




回答4:


without automatic variable [generally what we use in function in most cases] all other variable's value is assigned to 0




回答5:


Global variables are initialized as 0. Automatic variables (i.e. non-static locals) are not automatically initialized.



来源:https://stackoverflow.com/questions/5972978/what-does-printf-print-for-an-unitialized-variable

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