开发者

Interesting things of ! operation in bool value

开发者 https://www.devze.com 2023-02-12 15:34 出处:网络
Following are one code snippet #define T 0xFF using namespace std; int main(void) { char c = T; bool *pc = (bool *)(&c);

Following are one code snippet

#define T 0xFF
using namespace std;
int main(void) {
    char c = T;
    bool *pc = (bool *)(&c);
    bool nc = !(*pc);
    cout << "print: " << hex << nc <开发者_JS百科< endl;

    nc = T;
    cout << "print: " << hex << nc << endl;

    nc = c;
    cout << "print: " << hex << nc << endl;
}

The results is

print: fe
print: 1
print: 1

If type cast a char to a bool using the value 0xFF, bool value is 1.

But when type cast a char pointer to a bool pointer, 0xFF becoming 0xFE, only the last bit was flipped by ! operation.

Seems that gcc assumes a bool to be either 0 or 1 and if constructor of bool object is not called, it will just interpret the memory to contain a bool and flip the least significant bit.

But when bool is set by a char, does it trigger the copy contructor? But why different?


A bool can only take the values true and false.

When you perform !(*pc) you are getting undefined behavior because you telling the compiler to perform ! on a bool object when in actual fact pc is pointing at a char object. (It is the C style cast from char* to bool* that is dangerous, even though the undefined behavior only occurs when you apply the ! operator.)

When you convert a char or an int (e.g. 0xFF) to a bool all non-zero values are converted to true and zero values are converted to false.

0

精彩评论

暂无评论...
验证码 换一张
取 消