Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a float to a string reference works—why? [duplicate]

Tags:

c++

reference

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?

like image 843
s3cur3 Avatar asked Jun 07 '16 21:06

s3cur3


People also ask

What happens when you assign a float to an int?

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.

Can you add int and float python?

Integers and floating-point numbers can be mixed in arithmetic. Python 3 automatically converts integers to floats as needed.

What will be the result of a 5 3 if A is float and int?

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.


1 Answers

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.

like image 155
M.M Avatar answered Sep 28 '22 08:09

M.M