views:

58

answers:

4

Like if I have in my .h file:

int index;

and then in the .m file I have:

if(index == nil)

and I haven't assigned a value to index, will that come up true?

Thanks.

EDIT: I guess nil is only used for objects. So what is the state of an int that hasn't been assigned a value?

+1  A: 

The variable is technically undefined (may have any value) before you assign it a value. Most likely, it will be equal to zero. Also, both nil and NULL are defined to zero. However, this comparison is not recommended. You should only use nil when comparing pointers (it is not intended to be used with primitives).

Kevin Sylvestre
most likely, *but not always.* @Kevin has it right, and you should always initialize variables.However, `int`'s which are ivars for objects *are* initialized to 0 upon calling `[obj init];`
Stephen Furlani
A: 

nil is a specific value reserved for Objective-C object pointers. It is very similar to NULL (0) but has different semantics when used with message passing.

local primitive data types like int's are not initialized in Objective-C. The value of index will not be defined until you write to it.

void foo () {
   //initialize local variable
   int x = 5;
}

//initialise static variable
static int var = 6; 
Akusete
They're initialized to 0 if they have static storage duration, right?
Matthew Flaschen
I don't think any primitive types are initialized in C/Objective-C you should _always_ initialize primitive variables yourself.
Akusete
Variables with static storage duration are definitely zero-initialized in C (C99 §6.7.8.10).
Matthew Flaschen
I stand corrected.
Akusete
+2  A: 

There is no such thing as "nil" for ints. That's an object value. As for what variables are initialized to by default:

  • Non-static local variables are not initialized to any defined value (in practice, they will usually have whatever bit pattern was previously in the memory they're occupying)
  • Static variables are initialized to 0
  • Global variables are initialized to 0
  • Instance variables are initialized to 0

Note that the first rule above also applies to local object variables. They will not be nil-initialized for you. (Instance variables with object types will be, though.)

Chuck
+1  A: 

The value of an integer that hasn't yet been assigned depends on its declaration - an int with static storage duration is zero if you don't assign it anything else. An int with automatic or allocated storage duration could have any value if you don't explicitly initialize it.

By the way, putting an object declaration in your header like that is bound to cause you pain later.

Carl Norum