Concatenating two literals...

T

TheCoder

Why does this work:

It seems that we're concatenating two literals:

std::cout << greeting + name + " Hello " + "There" << std::endl;


but if you remove (greeting + name +), it doesn't work ?
 
A

Alan Johnson

Why does this work:

It seems that we're concatenating two literals:

std::cout << greeting + name + " Hello " + "There" << std::endl;


but if you remove (greeting + name +), it doesn't work ?

operator+ is left associative. So what you get is:
(((greeting + name)) + " Hello ") + "There"

Assuming greeting and/or name is of type std::string, then it is easy to
follow along as see that each subexpression is a std::string.

Remove the (greeting + name +) and all you are left with is trying to
add two string literals, which does not result in concatenation. If you
want to concatenate two string literals, simply put them next to each
other with no operator:
std::cout << " Hello " "There" << std::endl;

This will concatenate them AT COMPILE TIME.
 
M

MrNewsReader

operator+ is left associative. So what you get is:
(((greeting + name)) + " Hello ") + "There"

But why are there three braces ? wouldn't two be enough ? like:

((greeting + name) + " Hello ") + "There"

it seems nicer ;-)
 
K

kwikius

Why does this work:

It seems that we're concatenating two literals:

std::cout << greeting + name + " Hello " + "There" << std::endl;

but if you remove (greeting + name +), it doesn't work ?

to concat 2 string literals just remove the '+'. Then the preprocessor
does it for you. (Mainly useful to split a string literal over
multiple lines).

Welcome to another oddity of C++. If you don't like it you could
always try the D language where the syntax you are using would work
AFAIK


#include <string>
#include <iostream>

int main()
{
std::string greeting("something"), name("name");
std::cout << greeting + " " + name + " Hello " "There\n";
}

regards
Andy Little
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top