-2

I'm use to use gcc and g++ with -Wall and -Wextra flags since I don't want my code to contain any warnings. Sometimes I understand the reason why I should solve the warnings that comes up after compiling but some other times I don't. One example is the following warning:

warning: comparison of integer expressions of different signedness: ‘int’ and ‘unsigned int’ [-Wsign-compare]

To solve this warning I check the consistency of the int (or unsigned int, it depends on the cases) and the convert one type to the other. My question is: what are the possible hazard of not perform this checks?

j0s3
  • 13
  • 1
  • 2
  • 3
    The rules (simplifying somewhat) say that the signed value is converted to unsigned before the comparison happens. This leads to counter intuitive results, for example signed `-1` will be greater than unsigned `0`. In other words the behaviour is well defined, it's just not what most people expect. – john Sep 12 '20 at 11:46
  • One possible hazard is various kinds of bugs. The number of possible bugs in C++, due to these kinds of errors, are unlimited. – Sam Varshavchik Sep 12 '20 at 11:47
  • 1
    Does this answer your question? [Comparison operation on unsigned and signed integers](https://stackoverflow.com/questions/2084949/comparison-operation-on-unsigned-and-signed-integers) – Den-Jason Sep 12 '20 at 11:49

1 Answers1

0

Integers and unsigned integers have the same amount of bits. However, for the signed integer, because of the way one's complement (and with c++20 two's complement) works, the first bit can be interpreted as a “sign bit“: When it is 1, the number is negative.

So an unsigned int with a 1 as first bit is a very large number, whereas a signed int with a 1 as first bit is a negative number. Comparing the two numbers will thus not work, which is why you have to provide an explicit conversion.

Skusku
  • 558
  • 5
  • 11