Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force a C compiler to produce integer narrowing warning

Let's consider the following example:

#include <stdio.h>

void func(unsigned char c) {
   printf("0x%x\n", c);
}

int main() {
   int val = 0x11223344;
   func(val);
}

To my best knowledge, there is no way I can force gcc nor clang, to show a warning on the statement func(val) about the narrowing int -> unsigned char that will happen there. Not even by compiling with -Wall -Wextra -pedantic. The question targets mainly C code, but it is worth including the C++ world in the discussion as well (see the note below).

C++ Note

I'm well aware that in C++ exists a kind-of workaround using the uniform initialization syntax:

func({val});

But that does not solve my problem because:

  • for preexisting code, it requires changes
  • for new code, it would require using {} everywhere

Question 1

Is there any arcane option to achieve that when compiling C or C++ code? I'm fine also with a non-standard solution as long as it works with gcc or clang and it does not require changing the code. Note: I'm not looking for tricky C++ solutions using custom integer types with or without macros that wrap primitive types. I'm looking for something like a command-line option or a pragma. Again, the question is mostly for C code, but it's worth exploring any C++ solutions too.

Question 2 (fall-back)

If the reality turns out to be that (as suspected) no such solution exists, I'd be super-curious to understand why. I can't believe that such an option was just never considered to be implemented. There should be a list of reasonable arguments against it, that I just can't think of. But the thing is that the option could be simply non-standard like -fwrapv and people could use it only where it is really needed.

like image 922
vvaltchev Avatar asked Jan 18 '19 16:01

vvaltchev


1 Answers

Is -Wconversion what you're looking for?

You can see the behavior here, with a lot of cases.

like image 126
okovko Avatar answered Nov 13 '22 02:11

okovko