5

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?!

jscs
  • 63,694
  • 13
  • 151
  • 195
aryaxt
  • 76,198
  • 92
  • 293
  • 442

4 Answers4

22

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.

Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
6

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.)

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
5

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.

Blindy
  • 65,249
  • 10
  • 91
  • 131
-1

Instance variables are initialized to 0 before your initializer runs..

ref:

Community
  • 1
  • 1
kainan
  • 175
  • 2
  • 4