I'm wondering why it's the case that these two numbers are comparing equal. I had a (maybe false) realisation that I messed up my enums, because in my enums I often do:
enum class SomeFlags : unsigned long long { ALL = ~0, FLAG1 = 1, FLAG2 };
And I thought that 0 being an int and being assigned to an unsigned long long, that there was a mistake.
unsigned long long number1 = ~0;
/* I expect the 0 ( which is an int, to be flipped, which would make it
the max value of an unsigned int. It would then get promoted and be
assigned that value to an unsigned long long. So number1 should
have the value of max value of unsigned int*/
int main()
{
unsigned long long number2 = unsigned long long(0);
number2 = number2 - 1;
/* Here I expect number2 to have the max value of unsigned long long*/
if (number1 == number2)
{
std::cout << "Is same\n";
// They are the same, but how???
}
}
This is really confusing. To emphasise the point:
unsigned long long number1 = int(~0);
/* I feel like I'm saying:
- initialize an int with the value of zero with its bits flipped
- assign it to the unsigned long long
And this somehow ends up as the max value of unsigned long long???*/
Comparing Numbers means identifying a number that is smaller or greater than the rest. We can compare numbers using different methods such as on a number line, by counting, or by counting the number of digits, using place values of the numbers, etc.
In math, to compare means to examine the differences between numbers, quantities or values to decide if it is greater than, smaller than or equal to another quantity. Here, for instance, we are comparing numbers. By comparing, we can define or find by how much a number is greater or smaller.
Comparing numbers is the ability to determine more and fewer, greater than, less than and equal to, and putting a group of numbers in order. Comparing numbers is a relational number skill where students work with numbers in relation to each other.
cppreference: "The result of operator~
is the bitwise NOT (one's complement) value of the argument (after promotion."
No promotion (to int
or unsigned int
) is however needed here - but flipping all bits in a signed
type with the value 0
will make it -1
(all bits set) which when converted to an unsigned
type will be the largest value that type can hold.
To avoid this, make 0
unsigned
. The result of ~0U
will be an unsigned int
with all bits set, which can be converted to any larger unsigned
type perfectly.
unsigned long long number1 = ~0U;
You seems to be thinking that the conversion of int
to long long
is done just by prepending 0 in front of the int
. While this is true for the conversion of positive integer, it's not true for negative integers.
unsigned long long number1 = ~0
is identical as
unsigned long long number1 = -1
So when the conversion takes place, it is not simply copying the bits into number1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With