Reputation: 2755
So I've been going back and forth from C++, C# and Java lately and well writing some C++ code I did something like this.
string LongString = "Long String";
char firstChar = LongString.at(0);
And then tried using a method that looks like this,
void MethodA(string str)
{
//some code
cout << str;
//some more code }
Here's how I implemented it.
MethodA("1. "+ firstChar );
though perfectly valid in C# and Java this did something weird in C++.
I expected something like
//1. L
but it gave me part of some other string literal later in the program.
what did I actually do?
I should note I've fixed the mistake so that it prints what I expect but I'm really interested in what I mistakenly did.
Thanks ahead of time.
Upvotes: 0
Views: 245
Reputation: 361522
MethodA("1. "+ firstChar ); //your code
doesn't do what you want it to do. It is a pointer arithmetic : it just adds an integral value (which is firstChar
) to the address of string-literal "1. "
, then the result (which is of char const*
type) is passed to the function, where it converts into string
type. Based on the value of firstChar
, it could invoked undefined behavior. In fact, in your case, it does invoke undefined behavior, because the resulting pointer points to beyond the string-literal.
Write this:
MethodA(string("1. ")+ firstChar ); //my code
Upvotes: 2
Reputation: 13486
String literals in C++ are not instances of std::string
, but rather constant arrays of char
s. So by adding a char
to it an implicit cast to character pointer which is then incremented by the numerical value of the character, whick happened to point to another string literal stored in .data section.
Upvotes: 1
Reputation: 208373
The problem is that "1. "
is a string literal (array of characters), that will decay into a pointer. The character itself is a char
that can be promoted to an int
, and addition of a const char*
and an int
is defined as calculating a new pointer by offsetting the original pointer by that many positions.
Your code in C++ is calling MethodA
with the result of adding (int)firstChar
(ASCII value of the character) to the string literal "1. "
, which if the value of firstChar
is greater than 4 (which it probably is) will be undefined behavior.
Upvotes: 2
Reputation: 157374
C++ does not define addition on string literals as concatenation. Instead, a string literal decays to a pointer to its first element; a single character is interpreted as a numeric value so the result is a pointer offset from one location in the program's read-only memory segment to another.
To get addition as concatenation, use std::string
:
MethodA(std::string() + "1. " + firstChar);
Upvotes: 3
Reputation: 55897
MethodA(std::string("1. ")+ firstChar );
since "1. " is const char[4] and has no concat methods)
Upvotes: 3