-声明时变量的默认值- [英] - Default value of variables at the time of declaration -
问题描述
在初始化变量之前,我想知道变量的默认值是什么...
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 ?
此处有更多示例:
//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];
感谢您的回答。
推荐答案
答案是,它取决于定义变量的范围。
The answer is that it depends on the scope in which the variable is defined.
由于分配的内存为零,因此Objective-C对象的实例变量始终初始化为0 / nil / false。
Instance variables of Objective-C objects are always initialised to 0/nil/false because the memory allocated is zeroed.
全局变量为可能初始化为0 / nil / false的原因是,当首次将内存分配给进程时,操作系统也会将其清零。但是,理所当然的是,我从不依赖于此,并且总是自己对它们进行初始化。
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.
局部变量是未初始化的,并且根据堆栈的增长方式将包含随机数据/ shrunk。
Local variables are uninitialised and will contain random data depending on how the stack has grown/shrunk.
NB用于指向Objective-C对象的指针,您可以安全地将消息发送到nil。因此,例如:
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
这篇关于-声明时变量的默认值-的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!