Does an int in Objective-C have a default value of 1?
Asked Answered
H

4

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

Homologate answered 12/5, 2011 at 15:48 Comment(0)
H
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.

Haughay answered 12/5, 2011 at 15:50 Comment(0)
E
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.)

Ethelred answered 12/5, 2011 at 15:50 Comment(0)
A
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.

Arawakan answered 12/5, 2011 at 15:50 Comment(0)
P
-1

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

ref:

Polygraph answered 8/5, 2014 at 8:31 Comment(1)
the question is not about instance variables.Ulla

© 2022 - 2024 — McMap. All rights reserved.