Understanding the signed comparison vs unsigned

Can someone tell me why the if condition is false?

#include <iostream> using namespace std; int main(int argc, char *argv[]) { int a; unsigned int ua; a = -1; ua = a; cout << "ua: " << ua << endl; if (ua != -1) cout << "Is unsigned" << endl; else cout << "Is signed" << endl; return 0; } 

I mean, here ua == int_max_value, this is NOT -1, but when I run this, the output

Signed by

+6
source share
2 answers

!= and == on arithmetic types perform the so-called ordinary arithmetic conversions on their operands. Here we apply one operand of type unsigned X and one operand of type signed X , where X is one of int , long and long long , ordinary arithmetic conversions convert the signed operand to unsigned type before performing the comparison.

Therefore, when you compare ua (of type unsigned int ) and -1 (of type signed int ), -1 converted to type unsigned int (conceptually, adding 2 32 assuming a 32-bit int ), and the result is compared with the value of ua .

+4
source

Expected behavior != Will perform normal arithmetic conversions on operands if they are arithmetic types. This is described in the standard section of the C ++ 5.10 Equality project, which states:

If both operands are of arithmetic or enumeration type, normal arithmetic conversions are performed on both operands; each of the operators must give true if the specified relationship is true and false if it is false.

in this case, it will result in integer advancement that will see -1 converted to unsigned int. This is described in paragraph 5 , which states:

Otherwise, if the operand having an unsigned integer type has a rank greater than or equal to the ranks of the type of the other operand, the operand with a signed integer type must be converted to the operand type with an unsigned integer.

+1
source

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


All Articles