23

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 have a strong recollection of this being a warning, something along the lines of "Possible loss of precision". Was it removed or is my memory playing tricks on me?

How can i turn this into a warning in g++? I find this a useful warning, or is it a bad idea?

I can't even find anything appropriate at http://gcc.gnu.org/onlinedocs/gcc-4.4.5/gcc/Warning-Options.html

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67

3 Answers3

28
$ gcc -Wconversion test.c

test.c: In function ‘main’:
test.c:3: warning: conversion to ‘int’ from ‘double’ may alter its value
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 5
    Yes this does the trick. I find it really odd that it's not included in -Wall. – Captain Giraffe Apr 05 '11 at 14:16
  • 2
    It causes hundreds of warnings with integer related conversions, and this is why its is not enabled in `-Wall`. Maybe with https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53001 it will be simpler. – kwesolowski Sep 03 '14 at 12:05
22

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

Nawaz
  • 353,942
  • 115
  • 666
  • 851
8

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)

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345