c - 如何在 C 中切换 int/_Bool

标签 c boolean int toggle

假设我们有一个 int 并希望以 boolean 方式在 01 之间切换它。我想到了以下几种可能:

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...
  1. 第三个似乎有效。为什么?谁决定 !01
  2. 这些有什么问题吗?
  3. 还有其他可能性吗?例如按位运算符?
  4. 哪个性能最好?
  5. 是否所有这些都与 _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/

相关文章:

c - 为什么这段代码在 64 位架构上会出现段错误,但在 32 位架构上却能正常工作?

c - 如何在C编程中验证电话号码

python - 接受争论

c - 大中央调度使我的执行时间变慢

java - 多条件案件怎么办?

boolean - XOR 可以使用 SKI 组合器表示吗?

c# - 具有两个Int16的C#GetHashCode,还最多返回Int32吗?

java - 比较具有涉及 boolean 值的多个属性的列表

c# - C#中如何将整数转换为字符?

swift - NSDictionary 在检索信息时返回一个可选的整数