g++ -Wall not warning about double-> int cast

后端 未结 3 472
名媛妹妹
名媛妹妹 2020-12-03 14:02

In the following snippet no warnings are produced. g++4.4.3 -Wall -pedantic

//f is
void f(int );

f(3.14);
double d = 3.14;
int i = d+2;

I

相关标签:
3条回答
  • 2020-12-03 14:10
    $ gcc -Wconversion test.c
    
    test.c: In function ‘main’:
    test.c:3: warning: conversion to ‘int’ from ‘double’ may alter its value
    
    0 讨论(0)
  • 2020-12-03 14:21

    Apart from what other answers mention it is also worth mentioning that in C++0x {} initialization doesn't narrow. So instead of getting a warning you'll get an error for example

    void f(int x)
    {
       // code
    }
    
    int main()
    {
       f({3.14}); // narrowing conversion of '3.14000000000000012434497875801753252744674682617e+0' from 'double' to 'int' inside { }
    }
    

    g++ 4.4 and above support initializer list (with -std=c++0x option)

    0 讨论(0)
  • 2020-12-03 14:27

    Use -Wconversion option. -Wall doesn't include it.

    With -Wconversion option, GCC gives these warning messages:

    warning: conversion to 'int' alters 'double' constant value
    warning: conversion to 'int' from 'double' may alter its value

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