I tried compiling the following program with g++ for Windows (MingW) version 4.6.1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
int main()
{
int i;
long l=100;
double f=0.15;
cout<<sizeof(int)<<endl<<sizeof(long)<<endl<<sizeof(double)<<endl;
// Expected a warning for line below, but never go it
i=l; i=f;
cout<<"i= "<<i<<" l= "<<l<<" f= "<<f<<endl;
return 0;
}
When building with -Wall option, I did not get any warning about casting either float or long to int. The sizes of the different types were int=4 (bytes),long=4, and double=8.
Can someone explain why the warning was not thrown?
> Expected a warning for line below, but never go it
> i=l; i=f;
You need to enable -Wconversion explicitly - it is turned off by default.
In C++11, narrowing conversions enclosed in {} would generate an error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main()
{
int i ;
longlong ll = 8LL ;
double f = 4.0 ;
// with -Wconversion
i = ll ; // warning: conversion to 'int' from 'long long' may alter its value
i = f ; // warning: conversion to 'int' from 'double' may alter its value
// with --std=c++0x
i = {ll} ; // C++11: error: narrowing conversion from 'long long' to 'int' inside {}
i = {f} ; // C++11: error: narrowing conversion from 'double' to 'int' inside {}
}
@Duoas: I thought an explicit cast was when I specified the casting operator as below:
int i;float f;
i = (int)f;
OR
i = int(f);
In this case, I am not doing this. How is this an explicit cast?
@JLBorges: The -Wconversion option did throw up the warning for the double->int cast but not for the long->int cast. Is this because they are both the same size (4 bytes) on my machine?
> Is this because they are both the same size (4 bytes) on my machine?
It is because there would be no alteration in value (the conversion does not loose information) on your implementation.
Likewise, in C++11 this would not generate an error:
1 2 3 4
constlonglong ll = 78LL ;
// this would generate an error if 'll' is not a constexpr
// or if it has a value which is outside the range of values an int can hold
int i = {ll} ;