Reputation: 20800
why this code compiles?
std::string a = "test"
"a";
I know that " is ignored inside a string if \ is missing and this:
std::string a = "test""a";
will be the same as "testa" but why it compiles when I have space/tab/end of line inside it?
Upvotes: 1
Views: 656
Reputation: 47498
Whitespace ("space/tab/end of line", as you put it) between adjacent string literals is also ignored.
Since you want to know if this is standard, the C++ standard says:
2.1[lex.phases]/3
The source file is decomposed into preprocessing tokens (2.4) and sequences of white-space characters
2.1[lex.phases]/6
Adjacent ordinary string literal tokens are concatenated.
And white-space characters are defined in 2.4[lex.pptoken]/2 as
space, horizontal tab, new-line, vertical tab, and form-feed
Also, the example of such concatenation, provided in 2.13.4[lex.string]/3 involves space:
[Example:
"\xA" "B"
contains the two characters ’\xA’ and ’B’ after concatenation
which shows that the meaning of "adjacent tokens" in this case includes "separated by space", and therefore, "separated by a sequence of white-space characters", which includes new-line as well.
Upvotes: 9
Reputation: 12469
It's by design so you can have
std::string a = "really"
"long"
"string literals"
"spread over multiple lines";
Upvotes: 2
Reputation: 385405
Because the C++ grammar doesn't care about newlines, tabs or whitespace between tokens (as far as possible).
This is valid in much the same way that:
int a = 3 +
5 +
9;
is valid.
(Of course you often need some whitespace between tokens to set them apart, e.g. int a;
rather than inta;
. But as long as the distinction isn't required, the whitespace does not matter, e.g. 3 + 5
or 3+5
.)
Upvotes: 4
Reputation: 191058
The compiler is smart enough to optimize this for you.
C++ ignores end of lines in statements - the semicolon determines when the statement is complete.
Upvotes: 1