Unsigned vs. Signed Integers

David Klempfner
Level Up Coding
Published in
Dec 13, 2019

--

Photo by Robert F. on Unsplash

What will be the output of the following C code?

Output: x is greater

Why?

Because x is signed integer, y is unsigned integer. When the computer compares both of them, x is promoted to an unsigned integer type.
When x is promoted to unsigned integer, -2 becomes 65534 which is definitely greater than 10.
Why does it get converted to 65534? Go here to find out.
This interchanging of signed/unsigned numbers can lead to security bugs as described here.

Note that the equivalent code in C# produces the intuitive result of “y is greater”:

This is because both uint and int get promoted to long before the comparison.

You can read more about this and the rules for other binary numeric promotions on the MSDN website.

--

--

I’m a software developer who is passionate about learning how things work behind the scenes.