On a recent project, I ran into an error where I accidentally assigned a float to a string reference (instead of converting the float to a string, then assigning it).
The code looked something like this (tested under both Xcode/Apple LLVM 7.1 and GCC 4.9.2):
#include <iostream>
using namespace std;
static void get_text(string &s) {
s = 1.0f; // Legal (not even a warning!)
}
// This version gives a compiler error (as I'd expect)
// static void get_text(string &s) {
// string out = 1.0f;
// s = out;
// }
int main() {
string s;
get_text(s);
cout << s << endl; // Prints garbage
return 0;
}
Printing the string obviously results in garbage, but I'm not clear why this didn't give so much as a warning. (My best guess is that the compiler did some sort of implicit reinterpret cast to go from float, to int, to a memory address...?)
Is there a warning I could enable (in Xcode, ideally) that would prevent this sort of thing in the future?
Since a float is bigger than int, you can convert a float to an int by simply down-casting it e.g. (int) 4.0f will give you integer 4. By the way, you must remember that typecasting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value.
Integers and floating-point numbers can be mixed in arithmetic. Python 3 automatically converts integers to floats as needed.
If a fraction like 5/3 is assigned to float data type variable then it will store the complete value after the decimal. In the second case, we have 'a' as a variable of int data type which stores only integer values.
This is because of the member function:
string& operator=( char ch );
There is implicit conversion from floating point to integer types in C++ (char
is an integer type).
Normally you can use -Wfloat-conversion
in g++ to get a warning about this conversion, but I tried it and it didn't warn. (Maybe compiler bug?)
A simple way to modify the code to get errors for unexpected floating/integer conversions is:
s = { 1.0f };
Another option is to make the function have string
as return type (generally speaking this design is preferred to having an "out" reference parameter anyway):
static string get_text() { return 1.0f; }
Unfortunately this is one of many minor pitfalls surrounding the use of std::string
, which was "designed" when C++ was still very young and it was not apparent what undesirable long term consequences would arise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With