-2

I know Example 1 below is syntactically right but can the same be said about example 2?
Why is Example 2 not throwing a compiler error? I have never seen this form of C-string initialization in any C++ book I have read.

#include <iostream>
#include <string>

int main()
{
    //Example 1;
    const char STR_1[] = "your_cstring";
    std::cout << STR_1 << "\n\n";

    //Example 2
    const char STR_2[] =  "your_cstring  "
                          "your_cstring1 "
                          "your_cstring2 ";
    std::cout << STR_2 << "\n\n";  
}

Output:

your_cstring

your_cstring  your_cstring1 your_cstring2

Thanks a lot and much appreciated.

1

1 Answer 1

3

Adjacent string literals are concatenated.

This:

const char STR_2[] =  "your_cstring  "
                      "your_cstring1 "
                      "your_cstring2 ";

Is equivalent to this:

const char STR_2[] =  "your_cstring  your_cstring1 your_cstring2 ";

That being said, use std::string (C++) instead of char[] (C) unless you have a very good reason.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.