0

There are similar questions here but they related to particular case of usage in loop indexes. This one is more generic case. How to deal with this warning if there is no loops?

How to deal with the warning in this simplified case to outline the problem?

int(-3) >= size_t(31)
Sergei Krivonos
  • 4,217
  • 3
  • 39
  • 54

3 Answers3

2

Cast at least one of the operands so that they are both of the same signedness.

Be careful when casting unsigned to signed: if the value is too large, you will get implementation defined behaviour.

Be careful when casting signed to unsigned - the behaviour when the original value is negative is precisely defined, but it may be surprising. If the expression is rewritten as size_t(-3) >= size_t(31) then it is always true.

Note that the cast to int in the example is pointless - the literal 3 must be of type int, and applying unary - to that will give an int result.

2

It is a case-by-case basis, and you just have to use your knowledge of the problem you're solving to make that call. The goal is to avoid logic errors at runtime, not to stamp out warning messages.

Casting one or the other value to be the same as the other removes the warning, but won't prevent runtime problems due to logic errors.

e.g. if you had a large unsigned value and cast that to be signed, then it flips negative, which would mess up comparisions. Conversely, flipping -3 to unsigned will make it into a very large positive value, which would mess up the comparison you're trying. Sure, explicitly casting the values could avoid the messages but those messages are warning you about possible unexpected behaviour from your program, which you need to consider carefully regarding the possible & likely values that these variables can take.

Jason Lang
  • 1,079
  • 9
  • 17
0

To get answer which value is bigger use signed arbitrary arithmetic types like boost::cpp_int

auto v1 = int(-3);
auto v2 = size_t(31);
boost::cpp_int(v1) >= boost::cpp_int(v2);

If you have access to 80bit MMX registers then consider using them to store both values as signed and compare.

Sergei Krivonos
  • 4,217
  • 3
  • 39
  • 54