是对比较危险的是一个布尔? [英] Is comparing a BOOL against YES dangerous?

查看:169
本文介绍了是对比较危险的是一个布尔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个评论今天在源文件中:

I found a comment today in a source file:

//  - no longer compare BOOL against YES (dangerous!)

在Objective-C对比 BOOL 真的那么危险吗?为什么是这样?

Is comparing BOOL against YES in Objective-C really that dangerous? And why is that?

可以在运行时变化的价值?也许 NO 总是 0 ,但 1 2 3 - 根据运行时,编译器,你链接框架?

Can the value of YES change during runtime? Maybe NO is always 0 but YES can be 1, 2 or 3 - depending on runtime, compiler, your linked frameworks?

推荐答案

的问题是,BOOL是不是原生类型,而是一个typedef:

The problem is that BOOL is not a native type, but a typedef:

typedef signed char      BOOL;

#define YES             (BOOL)1
#define NO              (BOOL)0

作为一个字符,它的价值就不会被限制 TRUE FALSE 。与另一个值会发生什么?

As a char, its values aren't constrained to TRUE and FALSE. What happens with another value?

BOOL b = 42;
if (b)
{
    // true
}
if (b != YES)
{
    // also true
}

这篇关于是对比较危险的是一个布尔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆