逻辑运算符如何在目标c中使用常量操作数 [英] How Logical operators work with constant operand in objective c

查看:374
本文介绍了逻辑运算符如何在目标c中使用常量操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发项目,我在其中一个班级中使用 checkInternet 方法来验证互联网可用性。在该方法中,我有以下代码:

I am working on project where I have the checkInternet method in one of my class for verifying internet availability. In that method I have following code:

对于以下代码行,我收到警告,使用Logical&& with constant operand(旗帜&& kSCNetworkFlagsReachable)的强>

For below code of line I am getting warning that, "Using Logical && with constant operand" for this code of block (flag && kSCNetworkFlagsReachable).

BOOL isavailable = NO;
Boolean success;
isavailable = success && (flag && kSCNetworkFlagsReachable) && !(flag & kSCNetworkFlagsConnectionRequired);

并作为解决方案xcode提供使用& for bitwise operand的选项,我做的很好像这样,它删除了我的警告。
但我想知道它是如何工作的逻辑运算符?为什么它告诉我改为按位?

and as a solution xcode giving option that "Use & for bitwise operand" that's fine I do it like that and it removed my warning. But I want know how it was working logical operators? and Why it's telling me to change to for bitwise?

推荐答案

按位运算符 & 比较每一对位。仅当左右操作数至少有一个匹配位设置为1时,结果才为非空。

The bitwise operator & compares each individual pair of bits. The result will be non-null only if the left and right operands have at least one matching bit set to 1.

示例:0100 AND 0010→0000但0110 AND 0010 →0010。

Example : 0100 AND 0010 → 0000 but 0110 AND 0010 → 0010.

此运算符允许您使用单个整数值在不同位上存储多个布尔值,然后使用第二个值(称为掩码)来过滤比特。

This operator allows you to use a single integer value to store several booleans on different bits, then use a second value (known as a mask) to filter the bits.

kSCNetworkFlagsReachable 等于 1<< 1 2 )。因此, flag&仅当 flag 的第二个最低有效位设置为1时,kSCNetworkFlagsReachable 才为真。

kSCNetworkFlagsReachable is equal to 1<<1 (2). Thus, flag & kSCNetworkFlagsReachable is true only if the second least significant bit of flag is set to 1.

使用&& 代替& 是一个常见的错误。编译器将尝试检测该错误。在您的示例中, kSCNetworkFlagsReachable 是一个常量值。由于 kSCNetworkFlagsReachable 是常量且始终为真,因此测试 flag&& kSCNetworkFlagsReachable 为true与测试 flag 是否为真相同。因此,您不太可能真的想在逻辑运算中使用常量值。这就是编译器发出警告的原因。

Using && instead of & is a common mistake. The compiler will try to detect that mistake. In your example, kSCNetworkFlagsReachable is a constant value. As kSCNetworkFlagsReachable is constant and always true, testing whether flag && kSCNetworkFlagsReachable is true is the same as testing whether flag is true. Thus it is very unlikely that you really wanted to use a constant value in a logical operation. That's why the compiler emits the warning.

这篇关于逻辑运算符如何在目标c中使用常量操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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