Reputation: 77626
I have this simple line of code:
int x;
x
automatically has the value of 1. I don't set it to anything but when I debug, it shows that x
is 1.
Does an int
have a default value of 1?!
Upvotes: 5
Views: 6706
Reputation: 175
Instance variables are initialized to 0 before your initializer runs..
ref:
Upvotes: -1
Reputation: 67417
No, on the contrary, x
has no default value at all. What you're seeing is the garbage that the variable was placed upon when you created it.
Upvotes: 5
Reputation: 43472
No. int
has an undefined default value. It just happens to be 1
in this case. It could just as easily be -18382
or 22
or 0xBAADF00D
.
Always initialize your variables in C.
Upvotes: 22
Reputation: 281675
The initial value is undefined, and in this case will be whatever happened to be in that memory location before x
started using it.
(Depending on the surrounding code, you might find that in your specific case it's always 1
, but you can't be sure of that.)
Upvotes: 6