- Default value of variables at the time of declaration -

强颜欢笑 提交于 2019-12-12 09:47:01

问题


I was wondering what were the default values of variables before I initialized them...

For example, if I do :

//myClass.h

BOOL myBOOL; // default value ?
NSArray *myArray; // default value ?
NSUInteger myInteger; // default value ?

Some more examples here :

//myClass.m
// myArray is not initialized, only declared in .h file

if ([myArray count] == 0) { // TRUE or FALSE ?

// do whatever

}

More generally, what is returned when I do :

[myObjectOnlyDeclaredAndNotInitialized myCustomFunction];

Thank you for your answers.

Gotye.


回答1:


The answer is that it depends on the scope in which the variable is defined.

Instance variables of Objective-C objects are always initialised to 0/nil/false because the memory allocated is zeroed.

Global variables are probably initialised to 0/nil/false to because when memory is first allocated to a process, it is also zeroed by the operating system. However, as a matter of course, I never rely on that and always initialise them myself.

Local variables are uninitialised and will contain random data depending on how the stack has grown/shrunk.

NB for pointers to Objective-C objects, you can safely send messages to nil. So, for instance:

NSArray* foo = nil;
NSLog(@"%@ count = %d", foo, [foo count]);

is perfectly legal and will run without crashing with output something like:

2010-04-14 11:54:15.226 foo[17980:a0f] (null) count = 0



回答2:


by default NSArray value will be nil , if you would not initialize it.




回答3:


//myClass.h

BOOL myBOOL; // default value ?
NSArray *myArray; // default value ?
NSUInteger myInteger; // default value ?

the Bool myBool if not initialized will receive the default value of False.

NSArray *myArray if not allocated,initialized(for example NSArray *myArray = [[NSArray alloc] init];) will have the default value of NIL. if you call count on an unitialized array you will receive an exception not 0.

//myClass.m
// myArray is not initialized, only declared in .h file

if ([myArray count] == 0) { => here it should crash because of [myArray count]

// do whatever

}

for the NSUInteger myInteger the default value should be 0, the documentation says that this is used to describe an unsigned integer(i didn;t represent integers with this one though)

when you call [myObjectOnlyDeclaredAndNotInitialized myCustomFunction]; it should break, throw an exception.

hope it helps



来源:https://stackoverflow.com/questions/2635677/default-value-of-variables-at-the-time-of-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!