Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Casting operator ignored?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading