C99中的_Bool类型
21 March 2015
在读SDCC Compiler User Guide的时候读到下面一段:
bit
andsbit
types now consistently behave like the C99_Bool
type with respect to type conversion. The most common incompatibility resulting from this change is related to bit toggling idioms, e.g.:bit b; b = ~b; /* equivalent to b=1 instead of toggling b */ b = !b; /* toggles b */
In previous versions, both forms would have toggled the bit.
一直不明白说的什么意思,今天终于茅塞顿开。
首先,我们需要知道以下事实:
- 任何非零的值赋值给
_Bool
类型的变量b
,b
都会得到值1,而不会像其它unsigned
类型的变量一样截取; - 一元操作符
~
会对其操作数进行整数提升。
所以,即使b
的值是1,~b
首先会对b
进行整数提升,再取反,结果肯定是一个非零值,在赋值给b
,最终b
的值还是1。
blog comments powered by Disqus