iou*_*vxz 9 c++ bit-manipulation undefined-behavior
#include <stdio.h>
#include <iostream>
int main()
{
using namespace std;
uint64_t a = 3;
if (uint64_t(~a) == (~a))
cout << "right" << endl;//right
else
cout << "wrong" << endl;
cout << sizeof(~a) << endl;//8
uint8_t b = 3;
if (uint8_t(~b) == (~b))
cout << "right" << endl;
else
cout << "wrong" << endl;//wrong
cout << sizeof(~b) << endl;//4
getchar();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
~uint8_t返回int值,但〜uint64_t返回uint64_t.
这是未定义的行为吗?
结果
operator~是参数的按位NOT(一个补码)值(在促销之后).
整数提升施加到char,short int等(类型窄于int)并将结果需要在目的地为不被铸造到目的地类型int.
这就是sizeof(~b) == sizeof(int)你的理由.