1

In some code I today read, a type of C-String initialisation existed which is new to me.

It chains multiple String-Initialisation like "A""B""C"...

It also allows splinting the String Initialisation to multiple Lines

I set up a small Hello World demo, so you can see what I am talking about:

#include <stdio.h>

#define SPACE " "
#define EXCLAMATION_MARK "!"
#define HW "Hello"SPACE"World"EXCLAMATION_MARK

int main()
{
  char hw_str[] =
  "Hello"
  SPACE
  "World"
  "!";

  printf("%s\n",hw_str);
  printf("%s\n",HW);
  return 0;
}

So here are some questions:

  • is this valid according to the standard?
  • why this works? "abc" is like a array {'a','b','c'} right?, so why are array initialisations concatenated over multiple pairs of "" working?
  • has this feature an official name - like when you enter it in google, you find some documentation describing it?
  • is this portable?
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
schnedan
  • 234
  • 1
  • 9

1 Answers1

1

From the C Standard (5.1.1.2 Translation phases)

1 The precedence among the syntax rules of translation is specified by the following phases.

  1. Adjacent string literal tokens are concatenated

So for example this part of the program

char hw_str[] =
  "Hello"
  SPACE
  "World"
  "!";

that after macro substitutions looks like

char hw_str[] =
  "Hello"
  " "
  "World"
  "!";

is processed by the preprocessor in the sixth phase by concatenating adjacent string literals and you have

char hw_str[] =
  "Hello World!";
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • once I entered the phrase "Adjacent string literal" I found https://softwareengineering.stackexchange.com/questions/254984/on-concatenating-adjacent-string-literals , which is also a nice hint on that feature. – schnedan Jul 14 '21 at 20:10