我正在开发一个项目,其中我的班级中有checkInternet方法用于验证Internet可用性。 在该方法中,我有以下代码:
对于下面的代码行,我得到警告: “对逻辑代码块(flag && kSCNetworkFlagsReachable) 使用Logical && with constant operand” 。
BOOL isavailable = NO; Boolean success; isavailable = success && (flag && kSCNetworkFlagsReachable) && !(flag & kSCNetworkFlagsConnectionRequired);并作为一个解决方案xcode给出选项“使用和按位操作数”这很好,我这样做,它删除了我的警告。 但我想知道它是如何工作的逻辑运算符? 以及它为什么要让我改变为按位?
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:
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);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时,结果才是非空的。
例如:0100 AND 0010→0000,但是0110 AND 0010→0010。
该运算符允许您使用单个整数值在不同的位上存储多个布尔值,然后使用第二个值(称为掩码)来过滤这些位。
kSCNetworkFlagsReachable等于1<<1 ( 2 )。 因此,只有当flag & kSCNetworkFlagsReachable的第二个最低有效位被设置为1时, flag & kSCNetworkFlagsReachable为真。
使用&&而不是&是一个常见的错误。 编译器会尝试检测这个错误。 在你的例子中, kSCNetworkFlagsReachable是一个常量值。 由于kSCNetworkFlagsReachable是常量且始终为真,因此测试flag && kSCNetworkFlagsReachable是否为true与测试flag是否为true相同。 因此,你真的不想在逻辑操作中使用一个常量值。 这就是编译器发出警告的原因。
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.
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 is equal to 1<<1 (2). Thus, flag & kSCNetworkFlagsReachable is true only if the second least significant bit of flag is set to 1.
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.
更多推荐
发布评论