Why compiler allows narrowing conversions

前端 未结 3 1157
醉梦人生
醉梦人生 2020-12-16 05:30

Can anyone please explain to me, why the compiler allows initialize variables of built-in type if the initializer might lead to the loss of information?

For example

相关标签:
3条回答
  • 2020-12-16 05:51

    One of the features of initializer lists is that narrowing conversions are not allowed. But the language definition doesn't distinguish between warnings and errors; when code is ill-formed it requires "a diagnostic", which is defined as any message from a set of implementation-defined messages. Warnings satisfy this requirements. That's the mechanism for non-standard extensions: having issued a warning, the compiler is free to do anything it wants to, including compiling something according to implementation-specific rules.

    0 讨论(0)
  • 2020-12-16 05:52

    You can set the compiler flag to flag all warnings as error. In that case only it will stop you from doing like that. Otherwise it will only be a warning.

    0 讨论(0)
  • 2020-12-16 06:02

    This issue has been coming up lately. With gcc-4.7 a command line switch turns on the required behaviour:

    g++ -Werror=narrowing ...
    
    0 讨论(0)
提交回复
热议问题