I am converting a character to a string by concatenating it with an empty string (""). But it results in undefined behaviour or garbage characters in the resultant string. Why so?
char c = 'a';
string s = "" c;
cout<<s<<" "<<s.size()<<"\n";
CodePudding user response:
Let's look at your snippet, one statement or a line at a time.
char c = 'a';
This is valid, assigning a character literal to a variable of type char
.
Note: since c
is not changed after this statement, you may want to declare the definition as const.
string s = "" c;
Let's refactor:
std::string s = ("" c);
Let's add type casting to make the point more clear:
std::string s = ((const char *) "" (char) c);
The order of operations is resolve all expressions on the right hand side (rhs) of the assignment operator before assigning to the string variable.
There is no operator ()
in C that takes a const char *
and a single character.
The compiler is looking for this function: operator (const char *, char)
.
This is the primary reason for the compilation errors.
cout<<s<<" "<<s.size()<<"\n";
The string assignment and creation failed, thus s
is empty and s.size()
is zero.
CodePudding user response:
An interesting issue, which looks like an issue which the compiler does not detect at compilation.
I have tried this with GNU C 10.2 on Cygwin and your code snippet generates this.
0200312 (Fedora Cygwin 9.3.0-1) 31
if you replace char c = 'c';
with char c = '\0';
the output is
0
So looks like some kind of memory violation issue.
As you probably know, the standard method of appending a char is to use push_back
string s = "";
s.push_back(c);
cout << s << " " << s.size() << "\n";