Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this compile: string = int

Suppose the following code:

#include <iostream>
#include <string>

int func() { return 2; }

int main()
{
   std::string str("str");
   str = func();
   std::cout << "Acquired value: '" << str << "'" << std::endl;

   return 0;
}

Why does the line str = func(); compile without warning of a type mismatch?

I'm using compiler gcc v. 4.7.1 with the -std=c++11 flag set.

Output:

Acquired value: ''

like image 313
Frostfyre Avatar asked Mar 08 '16 19:03

Frostfyre


1 Answers

The std::string class includes an overloaded operator= that accepts a char value. Since char is an integer type, int is implicitly convertible to char.

The value being assigned to str isn't an empty string; it's a string of length 1 whose single character has the value 2 (Ctrl-B).

Try feeding your program's output to cat -v or hexdump.

$ ./c | cat -v
Acquired value: '^B'
like image 185
Keith Thompson Avatar answered Oct 04 '22 23:10

Keith Thompson