我知道在C和C++中,将bool转换为int时,
在下面的代码中,在使用Visual Studio 2013和Keil µVision 5编译的.c文件中,所有以下断言都成立。请注意,
C和C++标准对于将非零、非一的整数转换为bool有何规定?这种行为是否被详细说明?请包含引文。
(int)true == 1
,(int)false == 0
。我想知道反向转换的情况...在下面的代码中,在使用Visual Studio 2013和Keil µVision 5编译的.c文件中,所有以下断言都成立。请注意,
(bool)2 == true
。C和C++标准对于将非零、非一的整数转换为bool有何规定?这种行为是否被详细说明?请包含引文。
#include <stdbool.h>
#include <assert.h>
void TestBoolCast(void)
{
int i0 = 0, i1 = 1, i2 = 2;
assert((bool)i0 == false);
assert((bool)i1 == true);
assert((bool)i2 == true);
assert(!!i0 == false);
assert(!!i1 == true);
assert(!!i2 == true);
}
不是Can I assume (bool)true == (int)1 for any C++ compiler?的副本:
- 反向转换(int --> bool)。
- 在那里没有讨论非零、非一的值。
~0 == -1
的事实,我对True == -1
毫不惊讶;这就像在C中使用#define FALSE 0
后跟着#define TRUE ~(FALSE)
一样。 - user539810