假设我们有一个 int
并希望以 boolean 方式在 0
和 1
之间切换它。我想到了以下几种可能:
int value = 0; // May as well be 1
value = value == 0 ? 1 : 0;
value = (value + 1) % 2;
value = !value; // I was curious if that would do...
- 第三个似乎有效。为什么?谁决定
!0
是1
? - 这些有什么问题吗?
- 还有其他可能性吗?例如按位运算符?
- 哪个性能最好?
- 是否所有这些都与
_Bool
(或来自 stdbool.h 的bool
)相同?如果不是,有什么区别?
编辑:很多很棒的答案和很多有值(value)的信息,谢谢!很遗憾,我只能接受一个。
最佳答案
value = !value;
直接表达了你想做什么,它确实按照定义做了你想做的事情。
使用那个表达式。
来自 C99 6.5.3.3/5 “一元算术运算符”:
The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).
关于c - 如何在 C 中切换 int/_Bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13154073/