variable initialization in c.

+1 baskar k · November 26, 2015
CASE 1:            

#include
int main()
{
    int a;
    printf("%d\n",a);
}


In the case 1,  the compiler automatically assign zero or null value to  "a" variable . so the output will be zero.
CASE 2:  I used pointers to print the value of "a" variable. 

#include
int main()
{
    int a, *i = &a;
    printf("%d\n",*i);
}

In the case 2, the output is  "32767". my question is, why the compiler does'nt assign "zero" value for the "a" variable.
every time i run the case 2 program, it prints the same "32767" value and the value does'nt change. i think its not memory address.
please explain about this problem,  thank you.

Post a Reply

Replies

Oldest  Newest  Rating
+1 Dan P · November 26, 2015
When using a variable that is not initialised and not static the behaviour is undefined.
0 c student · November 27, 2015
for you to understand why this works, you need to know how memory works.  when you run the program, memory is allocated for your program to hold its contents.  in memory, an int means nothing but 32 bits of memory so when memory is allocated for your variable, whatever the contents are inside those 32 bits is what your variable holds.  your compiler may zero the 32 bits or it might not meaning it has values left inside it from previous program usage.
0 baskar k · November 28, 2015
THANK YOU VERY MUCH...
  • 1

C

107,270 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator