Assigning -1 to variable t
of type size_t
and checking it's equality with both -1 and 4294967295 (FFFFFFFF, 2's compliment of -1; my system is 64 bit;value may vary with system), then in both the cases, it returns 1 i.e. true.
Code is
int main(){
unsigned int t = 10;
cout<<"t = -1: "<<(t==-1); //checks if t is -1
cout<<"\nt = 4294967295: "<<(t==4294967295); //checks if t is 4294967295
cout<<"\nt: "<<t; //printing actual value of t
int p = t; //typecasting it to int
cout<<"\np: "<<p; //printing value of p
}
Actual output is
t = -1: 1
t = 4294967295: 1
t: 4294967295
p: -1
returning 1
for both checks (t==-1)
and (t==4294697295)
but outputs t = 4294697295
and outputs p = -1
.
Is it that the variable t is holding two values i.e. -1 and 4294697295.
Which is definitely not the case.
Help needed. What is actually happening inside the system??
When comparing signed value to unsigned, the signed value is converted to unsigned before comparison. This is done during compilation. So t==-1
becomes t==4294967295u
and t==4294967295
(signed integer literal) becomes t==4294967295u
.
Reference: http://eel.is/c++draft/expr.arith.conv
(1.5.3) Otherwise, if the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type shall be converted to the type of the operand with unsigned integer type.