Reputation: 3765
How to prevent this implicit type conversion between int and std::string, which is very bug prone. Here is the code.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s="string";
s = 123456789; //assign a int value to std::string
cout << s;
// your code goes here
return 0;
}
The code above can be compiled with no warning, and the result is obvious not what the coder intended. Can this be avoided?
Update: 123456789
will cause overflow warning if -Wall
flag is set. But if I changed into s = 98
, there will be no warning anymore. but I actually want the string to be the string 98
, not the ascii b
character. How to prevent this then?
Upvotes: 4
Views: 384
Reputation: 4343
From what I understand, you'd want a warning if something like this occurred. For that, you should enable all warnings. Add the -Wall -Wextra
flag while compiling.
However, you shouldn't need these flags in this particular case. If you haven't disabled warnings, you should get an implicit type conversion
warning.
As mentioned in comments, to enable a warning specifically for this case, you could use the -Wconstant-conversion
flag.
Upvotes: 4