Initialize C string with multiple quotes

I thought that a C string could be initialized with one and only one quotation mark. I'm just wondering how right this is?

char const help_message [] =   
   "Usage: %s [options] files ...\n"   
   "\n"   
   "Options include:\n"   
   " --verbose -v    Be verbose\n"   
   " --help -h       Print this help message\n"   
   " --output -o     Specify output file\n"     
   "\n" ;   

 printf (help_message, argv [0]) ;
+3
source share
5 answers

Adjacent string literals are concatenated, and this is useful in two ways: macros that concatenate strings and render multi-line string literals , such as you already above. Compare how this code would look different:

char const help_message[] = "Usage: %s [options] files ...\n\nOptions include:\n --verbose -v    Be verbose\n --help -h       Print this help message\n --output -o     Specify output file\n\n";

, . , , , , , '\n', . .

:

#define STRINGIZE_(v) #v
#define STRINGIZE(v) STRINGIZE_(v)

#define LOCATION __FILE__ ":" STRINGIZE(__LINE__)

#define MY_ASSERT(expr) do { \
   if (!(expr)) \
     some_function(LOCATION ": assertion failed in " \
                   __PRETTY_FUNCTION__ ": " #expr); \
} while (0)

( , GCC __PRETTY_FUNCTION__, , , "" , .)

, , :

  • # (## , )
  • , "filename.c:__LINE__"
  • do-while if-else , ,
    • , , assert-like

if-else:

if (cond) MY_ASSERT(blah);
else other();

:

if (cond) do { ... } while(0);
else other();

:

if (cond) if (...) ...;
else other();

:

if (cond) {
  if (...) {
    ...;
  }
  else {
    other();
  }
}
+2

.

, , :

#define LOG(x) printf("%s", "Logging: " x)

LOG("HeyHey");

, .

+12

. C .

+2

:

{"xxx" ,
"yyyy",
"3534"}

, , .

+2

Your initializer contains only one string literal. It seems that several "closed" string literals will actually be merged into one string literal at the 6th stage of translation (after preprocessing).

+2
source

Source: https://habr.com/ru/post/1724346/


All Articles