1

I am reading a book called "Programming in Objective-C", Sixth Edition, by Stephen G. Kochan. It has the following statement on page 144 which is confusing me:

Local variables that are basic C data types have no default initial value, so you must set them to some value before using them.

Yet when I have the following code, it still works, and displays 0:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    int number;
    NSLog(@"%i", number);

    return 0;
}

Isn't int a basic C data type?

jscs
  • 63,694
  • 13
  • 151
  • 195
user3451821
  • 123
  • 7
  • Closely related: [Initial value of int array in C](http://stackoverflow.com/q/1414215) – jscs May 01 '14 at 03:08
  • It works as long as you are running your code inside the debugger. The debugger does some magic to your applications memory initializing local variables with 0: http://www.flounder.com/debug_release.htm – user2378197 Jun 23 '15 at 15:19

2 Answers2

8

"Basic C data types have no default initial value", it does not mean they will not have a value if you do not initialize them, it is just that you will not know in advance what that value will be.

In your case, that number just happen to have a zero, but it could have other value.

Lee Duhem
  • 14,695
  • 3
  • 29
  • 47
  • So basically it is somewhat random? I should always initialize and cannot count on it always being 0? I read somewhere that it depends what is in the memory location at that specific time. – user3451821 May 01 '14 at 03:09
  • 2
    @user3451821 Yes, and Yes. – Lee Duhem May 01 '14 at 03:14
4

Local variables are allocated on the stack. The initial value of a local variable has no guaranteed value. Instead the value of the local variable depends entirely on whatever random values were left by the previous function that used that particular region of the stack.

In the case of the main function, the initial values of local variables may seem predictable since main is the first function to run and use that region of the stack. However, the compiler makes no effort, and the language specification has no requirement, to guarantee the initial value of the local variables.

In summary, always explicitly initialize local variables before using them.

user3386109
  • 34,287
  • 7
  • 49
  • 68