In this answer I'll address the compiler flags you can use to trackdown bugs related to implicit type promotion since I just ran intothis "feature". In the following buggy code fragment exp
is oftype uint32_t
:
for (int32_t i = 22; i >= MAX(22 - exp + 1, 0); i--) { ...}
If exp
< 23 code works fine, if exp
= 23 loop runs forever, and ifexp
> 23 loop never runs. The fix is to change the first argument toMAX
to 22 - (int32_t)exp + 1
. To make it easier to spot such bugs Irecommend turning on the warning -Wsign-compare
. It is included in-Wextra
, which may be a little heavy for everyday use.
The bug in the other example;
unsigned short a = 1;signed short b = -2;if(a + b > 0) puts("-1 is larger than 0"); // will not print
is caught by -Wsign-conversion
, also included in -Wextra
. In myown codebase this flag produces about 40 warnings all of which arecompletely benign and not worth the bother to fix.
Unfortunately, neither gcc nor clang has warnings for flagging"suspicious" type promotions, but leaving safe ones be (e.g for (int i = 0; i < strlen(s); i++)
).
You may want to read Friends don't let friends use"-W" for (informed) opinion onwhen and when not to use the compiler's warning flags.