Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does comparison operator works in case of overflow

Tags:

c++

c

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 ?

like image 470
Dexter Avatar asked Apr 11 '14 09:04

Dexter


2 Answers

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.

like image 108
herohuyongtao Avatar answered Oct 10 '22 03:10

herohuyongtao


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.

like image 37
david.pfx Avatar answered Oct 10 '22 03:10

david.pfx