DEV Community

CChall
CChall

Posted on • Edited on

Comparing signed and unsigned int in C

If you are here to know if it is safe?
In short, it depends. if both numbers are positive then you can ignore compiler warning, else you better listen to it.

Let's begin with why this knowledge was important for me.
So i have started working on my own game written from base in C. While i was doing so i decided to force unsigned int in struct so my window size cannot be set to negative number.
I thought it was good idea so no one will make this silly mistake but new problem has arisen. Later in code i was checking is window size is in monitor boundaries, it would be simple but library for window initialization when asked about monitor parameters returned values as int giving me warning when compared to my struct. So i was wondering is it safe to just ignore them ?

So i started googling about signed-unsigned comparison but what i could find was only cpp articles about std library function. So yea not a good start. After a while I found a good video WHY those warnings are crucial:
https://www.youtube.com/watch?v=c_iQQMkonjE = Comparing an int and an unsigned int

In short: when comparing int and unsigned int values, signed value is interpreted as unsigned.
For example -10 becomes then 4 294 967 286.

Why is that ?
Because we just take bytes and we start treat them differently.
In fact nothing behind the hood was changed:

when we look at binary of -10 in 32-bit system we can see:
11111111 11111111 11111111 11110110
Those are just zero and ones but we know this is SIGNED value so we know that this is just negative 10.
Well, we know it but when we decide to act like it is UNSIGNED value then the same binary:
11111111 11111111 11111111 11110110
is now 4 294 967 286.
Only way to diffrenciate it is to KNOW are we treating it as signed or no.
When comparing this 2 values compiler doesn't know that one is signed and other not. It acts like BOTH are unsigned.

But what about two positive numbers?
One signed and one unsigned, is it a problem ?
Short answer: no, you can do it safely.
Why is that?
Lets look into signed 15 in binary:
00000000 00000000 00000000 00001111
So let's look at 15 as unsigned:
00000000 00000000 00000000 00001111
We have same output, that's why it doesn't matter if both are positive.

So that's everything you have to know about this weird behavior.
May the safe code be with you!

Top comments (0)