Conversion from double to int by default
John (Eljay) Love-Jensen
Fri Apr 9 11:53:00 GMT 2010
> I am puzzled by the fact that g++ (4.4.1, 64-bit Gentoo) allows me to compile following line without any error: int value = 2.5;
> I tried to search the web but I still do not have any clue why it converts from double to int by default.
Since C++ has a lot of behavior it acquired from C, and C allows that implicit conversion from double to int, the C++ compiler has the same implicit conversion behavior.
> This seems pretty dangerous to me.
Agreed, this kind of implicit conversion seems pretty dangerous to me, too. The solution is to use a language which does not do that. C++ is not that language.
> Am I missing something?
Not really. You have discovered one of the questionable standard behaviors of C, and hence C++.
There are those (like myself) who find such behavior to be unfavorable. I presume that amongst C/C++ programmers, you and I are in a very small minority.
However, playing the advocate, there are many many many others who find such behavior to be preferable to some sort of "int value = DoubleToInt(2.5);" requirement. Implicit brevity over explicit verbosity.
The behavior is not going to change for C (ISO 9899) or C++ (ISO 14882). If it were to change, the resulting language would be "close to C++, but not C++".
If you want to curtail such implicit conversions, you can write your own "class Int" as a wrapper around an int, but which disallows the implicit conversions. See "class Year" in C++ Programming Language 11.7.1 (p285) as an example.
The "B&D" languages such as Ada eschew implicit conversions.
More information about the Gcc-help