Reputation: 55
Im trying to get my head around declaration and definition of variables in C. My learning material from school says that global uninitialised variables are assigned 0 whereas uninitialised local variables are left unassigned and have a value that was present in that memory address.
However, I tried a following very simple program:
#include <stdio.h>
void something(){
int third;
int fourth;
printf("third: %d\n", third);
printf("fourth: %d\n", fourth);
}
int main(){
int first;
int second;
printf("first: %d\n",first);
printf("second: %d\n",second);
something();
return 0;
}
Output is following:
first: 382501330
second: 32766
third: 0
fourth: 0
Second run:
first: 235426258
second: 32766
third: 0
fourth: 0
Observations:
Variable 'first' seems to be assigned a random number every time as expected
Variable 'second' is assigned the same number (32766) every time, why?
Why variables 'third' and 'fourth' are assigned to zeros as they are local, not global variables?
Upvotes: 3
Views: 497
Reputation: 60056
You're accessing uninitialized locals that could have been declared register
.
That's undefined behavior. Your program no longer makes sense.
If you fix it up by sprinkling in some &
operators (so that the locals no longer can have been declared register
)
#include <stdio.h>
void something(){
int third;
int fourth;
printf("third: %d\n", *&third);
printf("fourth: %d\n", *&fourth);
}
int main(){
int first;
int second;
printf("first: %d\n", *&first);
printf("second: %d\n", *&second);
something();
return 0;
}
then as far as C is concerned the values will be unspecified. What you'll get depends on your environemnt
and what the main-calling libc-routine left in the stack before it made the call to main
.
Upvotes: 2