iouvxz iouvxz - 4 months ago 35
C++ Question

C++ Why bitwise operator ~ on uint64_t and uint8_t return different types?

#include <stdio.h>
#include <iostream>

int main()
using namespace std;
uint64_t a = 3;
if (uint64_t(~a) == (~a))
cout << "right" << endl;//right
cout << "wrong" << endl;
cout << sizeof(~a) << endl;//8

uint8_t b = 3;
if (uint8_t(~b) == (~b))
cout << "right" << endl;
cout << "wrong" << endl;//wrong
cout << sizeof(~b) << endl;//4
return 0;

~uint8_t returns int value,but ~uint64_t returns uint64_t .

Is this undefined behaviour ?


Posting from en.cppreference

The result of operator~ is the bitwise NOT (one's complement) value of the argument (after promotion).

Integral promotion is applied to char, short int etc (types narrower than int) and the result needs to be casted to destination type if destination is not int.

This is the reason for sizeof(~b) == sizeof(int) in your case.