Reputation: 51
this is my first question so... nice to meet you! Could someone explain why this code written in C
#include <stdio.h>
int main(){
int choice;
printf("\nSize of 'choice' %d\n", sizeof(choice));
printf("Size of 'int' %d\n", sizeof(int));
printf("Value of 'choice %d\n", choice);
return 0;
}
compiled on Windows using gcc -o C:\test.exe test.c
(gcc version 2015/06/27) returns these values
Size of 'choice' 4
Size of 'int' 4
Value of 'choice 2
while on Linux everything works as I expected, returning these values
Size of 'choice' 4
Size of 'int' 4
Value of 'choice 0
What am I missing?
Thanks a lot.
Upvotes: 2
Views: 79
Reputation: 434
The value in the choice variable is not initialized so default value is undefined since it is a automatic storage class and it is different in different platforms
Upvotes: -1
Reputation: 741
You try to use variable without initialization. So, it can contains a random value
Upvotes: 1
Reputation: 42984
In your code you defined a variable without specifying an initial value, so you cannot pretend the variable to be automatically initialized to anything.
If you want your variable to be zero-initialized, please do so explicitly with =0
.
Upvotes: 3
Reputation: 17688
What am I missing?
You never initialise choice
in the first place. So the behaviour is undefined. It doesn't matter what compiler you are using, the value printed is just garbage value in the memory location of choice
.
Upvotes: 2
Reputation: 409404
Uninitialized local non-static variables are just that, uninitialized. They will have an indeterminate value. Using them without initialization leads to undefined behavior.
Upvotes: 7