Is there a gcc flag to catch integer truncation?

前端 未结 2 615
时光说笑
时光说笑 2021-01-18 10:51

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 -Wex

相关标签:
2条回答
  • 2021-01-18 11:28

    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.

    0 讨论(0)
  • 2021-01-18 11:42

    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.

    0 讨论(0)
提交回复
热议问题