作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
假设我们有一个 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/
我是一名优秀的程序员,十分优秀!