Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a gcc flag to catch integer truncation?

Is there a gcc flag to signal a warning/error when I try to put a double value into an int variable? I currently have -Wall -Wextra -Werror set but I still don't get warned when I (for instance) pass a double to an int parameter, even though I'm losing information.

like image 640
Sean Kelleher Avatar asked Mar 05 '14 12:03

Sean Kelleher


People also ask

How do I enable warnings in GCC?

GCC 4.3+ now has -Q --help=warnings , and you can even specify --help=warnings,C to just print out the C related warnings.

What is Wextra?

-Wextra , among other stuff implies -Wtype-limits : Warn if a comparison is always true or always false due to the limited range of the data type, but do not warn for constant expressions. For example, warn if an unsigned variable is compared against zero with '<' or '>='. This warning is also enabled by -Wextra.

How does GCC treat warning errors?

You can use the -Werror compiler flag to turn all or some warnings into errors. Show activity on this post. You can use -fdiagnostics-show-option to see the -W option that applies to a particular warning. Unfortunately, in this case there isn't any specific option that covers that warning.


Video Answer


2 Answers

You can use the -Wconversion option. From GCC's manual (emphasis mine):

Warn for implicit conversions that may alter a value. This includes conversions between real and integer, like abs (x) when x is double; conversions between signed and unsigned, like unsigned ui = -1; and conversions to smaller types, like sqrtf (M_PI). Do not warn for explicit casts like abs ((int) x) and ui = (unsigned) -1, or if the value is not changed by the conversion like in abs (2.0). Warnings about conversions between signed and unsigned integers can be disabled by using -Wno-sign-conversion.

This is the state uptill GCC 4.8.2, while from GCC 4.9.0 you may also use -Wfloat-conversion for the same.

like image 187
legends2k Avatar answered Oct 18 '22 08:10

legends2k


Yes, use the -Wfloat-conversion option:

-Wfloat-conversion

Warn for implicit conversions that reduce the precision of a real value. This includes conversions from real to integer, and from higher precision real to lower precision real values. This option is also enabled by -Wconversion.

like image 25
unwind Avatar answered Oct 18 '22 08:10

unwind