Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 750
Rajeev Kumar Avatar asked Jun 27 '12 19:06

Rajeev Kumar


People also ask

What is the value of an uninitialized variable?

INTRODUCTION: An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using.

What will be the value of a global variable that declared but not initialized?

I learned that if variables are declared but not assigned any value they are initialized with a random value (except static and global variables which are initialized with 0).

What happens if you attempt to access the value of an uninitialized variable in C?

Using the value stored in an uninitialized variable will result in undefined behavior.

What is the default value for an uninitialized reference variable?

An uninitialized reference doesn't have no value, it has an undefined value (and the compiler prevents you from using them, IIRC). A reference initialized to null will result in a equality comparison with null always evaluating to true .


1 Answers

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.

like image 187
Alok Save Avatar answered Oct 06 '22 22:10

Alok Save