What will be the value of uninitialized variable? [duplicate]

折月煮酒 提交于 2019-11-26 03:44:19

问题


This question already has an answer here:

  • (Why) is using an uninitialized variable undefined behavior? 7 answers

Possible Duplicate:
Is uninitialized data behavior well specified?

I tried the following code

#include<stdio.h>
void main()
{
int i; \\
printf(\'%d\',i);
}

The result gave garbage value in VC++, while same in tc was zero. What will be the correct value? Will an uninitialized variable by default have value of zero? or it will contain garbage value?

Next is on the same

#include<stdio.h> 
void main()
{
int i,j,num;
j=(num>0?0:num*num);
printf(\"\\n%d\",j);
}

What will be the output of the code above?


回答1:


Technically, the value of an uninitialized non static local variable is Indeterminate[Ref 1].
In short it can be anything. Accessing such a uninitialized variable leads to an Undefined Behavior.[Ref 2]

[Ref 1]
C99 section 6.7.8 Initialization:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

[Ref 2]

C99 section 3.18 Undefined behavior:

behavior, upon use of a nonportable or erroneous program construct, of erroneous data, or of indeterminately valued objects, for which this International Standard imposes no requirements.

Note: Emphasis mine.




回答2:


Accessing an unitialized variable is undefined behavior in both C and C++, so reading any value is possible.

It is also possible that your program crashes: once you get into undefined behavior territory, all bets are off1.


1 I have never seen a program crashing over accessing an uninitalized variable, unless it's a pointer.




回答3:


It's indeterminate. The compiler can do what it wants.




回答4:


The value is indeterminate; using the variable before initialization results in undefined behavior.




回答5:


It's undefined. It might be different between different compilers, different operating systems, different runs of the program, anything. It might not even be a particular value: the compiler is allowed to do whatever it likes to this code, because the effect isn't defined. It might choose to optimize away your whole program. It might even choose to replace your program with one that installers a keylogger and steals all of your online banking login details.

If you want to know the value, the only way is to set it.




回答6:


As others have noted, the value can be anything.

This sometimes leads to hard-to-find bugs, e.g. because you happen to get one value in a debug build and get a different value in a release build, or the initial value that you get depends on previous program execution.

Lesson: ALWAYS initialize variables. There's a reason that C# defines values for fields and requires initialization for local variables.



来源:https://stackoverflow.com/questions/11233602/what-will-be-the-value-of-uninitialized-variable

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