BOOL 是OC中对boolean 类型的定义,其被预定义为有符号的char类型,其值为 YES/NO,YES 被预定为 1 NO 被预定义为 0;其转化为整数的范围是-127至+127 ,可以将这之间的任意数赋给BOOL 类型的变量;一般情况下不要使用BOOL类型的变量和YES比较,因其结果可能不是你想要的。
BOOL定义源码:
typedef signed char BOOL;
#if __has_feature(objc_bool)
#define YES __objc_yes
#define NO __objc_no
#else
#define YES ((BOOL)1)
#define NO ((BOOL)0)
#endif
2、bool为GNU extension中对 boolean类型的变量的定义,其值为true和false;其中true 被预定义为1 ,false被预定义为0 ;非0的数赋值给bool变量则为1,将 只有0,nil,Nil,NULL 和没有初始化的 short,int,char,float赋值bool变量bool,bool变量的值才为0,其他任何值赋给bool变量其值都为1;没有初始化的变量可以赋值给bool变量,其真假值不定,此时编译器会警告你这样做.
测试发现其值与if,while,for中条件判断完全一致。bool定义源码
#ifndef __STDBOOL_H
#define __STDBOOL_H
/* Don't define bool, true, and false in C++, except as a GNU extension. */
#ifndef __cplusplus
#define bool _Bool
#define true 1
#define false 0
#elif defined(__GNUC__) && !defined(__STRICT_ANSI__)
/* Define _Bool, bool, false, true as a GNU extension. */
#define _Bool bool
#define bool bool
#define false false
#define true true
#endif
#define __bool_true_false_are_defined 1
#endif /* __STDBOOL_H */
#import <Foundation/Foundation.h>
int main(int argc,const char * argv[])
{
@autoreleasepool {
//BOOL 与 bool的区别
BOOL a =256;//定义为有符号的char类型
bool b =256;//非0的数赋给bool都是1
NSLog(@"b is %d",b);// b is 0
NSLog(@"a is %d",a);// a is 1
NSString *pupil =@"I,m a pupil";
BOOL e = pupil;
NSLog(@"e is %d",e);//e is -32
bool d= pupil;
NSLog(@"d is %d",d);//d is 1
d =nil;
NSLog(@"d is %d",d);//d is 0
d =Nil;
NSLog(@"d is %d",d);//d is 0
d=NULL;
NSLog(@"d is %d",d);//d is 0
d =12.2f;
NSLog(@"d is %d",d);//d is 1
}
return 0;
}