i have the following code :
int main() {
int64_t val1 = 0x8000000000000000;
int64_t val2 = 0x1c11223344556677;
if(val1 > val2) {
std::cout << "Val1 is greater than val2"<< std::endl;
}
else {
std::cout << "Val2 is greater than val1"<< std::endl;
}
return 0;
}
The get the print for else part of the code.
i wanted to know how does comparison operator or for that matter any arithmetic operation work in case one of the value exceeds the max value ?
According to C++11 §5:
If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.
The value 0x8000000000000000
is a large unsigned integer, 9223372036854775808 as a decimal.
The maximum value that can be stored in a 64-bit signed integer, represented by INT_64_MAX or similar, is 9223372036854775807.
The conversion of this value from unsigned to signed is covered in the standard at n3797 S4.7/3:
If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.
Since it cannot be so represented, the behaviour is implementation-defined.
What will actually happen on most implementations is that the bit value will be stored unchanged. Now val1 has a value that is outside the allowable range, and any use of it will result in Undefined Behaviour.
In particular the comparison between two signed integers, one of which is outside the allowable range, cannot be reliably predicted. It will probably defer to a specific instruction in the underlying machine hardware, so you would have to inspect the generated code to determine which that would be. I can write the code and tell you what I find, but for a different compiler or different processor it might be different.
Best advice is always to avoid Undefined Behaviour if you possibly can.
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