5

I'm new to c++ and I came across below code snippet which looks strange for me.

const char* keys = "hello" "world";
std::cout << keys << std::endl;

Above code prints helloworld in the console. Is it syntactically valid to assign two string literals to a const char* in the same statement? if so, how it will be stored in memory?

1
  • 1
    "hello" "world" == "helloworld" Commented Mar 22, 2019 at 8:11

2 Answers 2

5

It's a rule of C++ (and C) adjacent string literals are concatenated prior to compilation (but after macro expansion IIRC).

This happens anywhere, not just as part of an assignment statement.

Sign up to request clarification or add additional context in comments.

2 Comments

so the string literals are concatenated prior to compilation and stored contiguously in read only data segment.
They're stored contiguously, but using a read only data segment is an implementation detail that won't be true for some systems.
4

A character sequence within quotes (or even empty quotes) with or without an encoding prefix is a string-literal as per [lex.string].

And as per [lex.string]/13:

...adjacent string-literals are concatenated.

So

const char* keys = "hello" "world";

is same as:

const char* keys = "helloworld";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.