How the comparison operator works in case of overflow

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;
}

Get the fingerprint for more of the code.

I wanted to know how the comparison operator works or, if that is, any arithmetic operation, if one of the values ​​exceeds the maximum value?

+4
source share
4 answers

According to C ++ 11 §5:

If during the evaluation of an expression the result is not determined mathematically or not in the range of represented values ​​for its type, the behavior is undefined .

+4
source

The value 0x8000000000000000is an unsigned large integer, 9223372036854775808 as a decimal.

, 64- , INT_64_MAX , 9223372036854775807.

n3797 S4.7/3:

, , ( ); .

, .

, , . val1 , , Undefined .

, , . , , , , . , , .

- Undefined , .

+4

: val1 ( !), val2, .

#include <iostream>

int main() {
   int64_t val1 = 0x8000000000000000;
   int64_t val2 = 0x1c11223344556677;
   std::cout << "val1: " << val1 << std::endl;
   std::cout << "val2: " << val2 << std::endl;
   if(val1 > val2) {
      std::cout << "Val1 is greater than val2"<< std::endl;
   }
   else {
      std::cout << "Val2 is greater than val1"<< std::endl;
   }
   return 0;
}

(ideone):

val1: -9223372036854775808
val2: 2022435311251187319
Val2 is greater than val1
+1

, , .

The operator simply does not work, since int64_t is designed to store values ​​in the limit (-2 ^ 63 to 2 ^ 63-1). If you want to use more range, use the unsigned version. For even greater range, use some easily accessible bignum library or write it yourself. (For example, you can store large numbers in a string , and the comparison will become very simple)

+1
source

Source: https://habr.com/ru/post/1536070/


All Articles