-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.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
African_king
  • 177
  • 1
  • 8
  • 1
    Or this: https://stackoverflow.com/questions/32479995/quotation-mark-in-return-c or https://stackoverflow.com/questions/39327148/compilation-of-string-literals – T.J. Crowder Aug 20 '22 at 14:58

1 Answers1

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.

DevSolar
  • 67,862
  • 21
  • 134
  • 209