Why you might need -Wsign-compare for C code

Published 09 February 2012 under C, gcc

Here's a simple example of mixing signed and unsigned integers in C, does it do what you would expect?

By default, compilers such as gcc and clang (llvm) will compile the following code without warnings, even with -Wall set. If, as I did, you expect this to produce a return value of 42, then you're in for a surprise.

int main(void)
  int a = -27;
  unsigned b = 20U;
  if (a > b)
    return 27;
  return 42;

If you recompile this code with -Wsign-compare then you will get a warning about "comparison of integers of different signs". For C++, -Wsign-compare is included in the -Wall list of warnings, but not for C. For both gcc and clang -Wsign-compare is included in the -Wextra list of warnings.

So, if you're a user of C and you don't use -Wextra, now may be a good time to add it to your build system.


blog comments powered by Disqus