Having such simple code:
DWORD i = 0xFFFFFFF5; // == 4294967285(signed) == -11(unsigned)
if((unsigned)i == -11)
OutputDebugString(L"equal");
else
OutputDebugString(L"not equal");
The condition is meet – i’m getting "equal" output.
My question is WHY is that happen since in the condition we have
f(4294967285 == -11) considering the explicit unsigned cast on the left side of the operator? Why is the cast ignored?
>Solution :
DWORD is unsigned or equivalent, a 32-bit unsigned integer in your C++ implementation. DWORD i = 0xFFFFFFF5; initializes i to FFFFFFF516 = 4,294,967,285.
In (unsigned)i == -11, i is converted to unsigned, which yields the same value, 4,294,967,285. The other operand, -11, has type int and value −11.
When two numbers are compared with ==, they are converted to be some common type. The rules for operating on an unsigned and an int result in the int being converted to unsigned. When −11 is converted to unsigned in a C++ implementation in which unsigned is 32 bits, the result of the conversion is 232−11 = 4,294,967,296 − 11 = 4,294,967,285.
Then the two unsigned values are compared. Since they are both 4,294,967,285, the comparison indicates they are equal.