Nitin Tripathi
Nitin Tripathi

Reputation: 1254

C literals concatenation

C allows us to concatenate literal list via MACRO.

#define H "HELLO"
#define W "WORLD"
#define HW H " " W

It would result out in expansion of HELLO WORLD.

Same can be achieved via initialiser list.

char A[] = "Hello" " " "World";

It would also result out in expansion of HELLO WORLD.

Same applies to printf("%s\n", "HELLO" " " "WOLRD");.

even here, It would result out in expansion to HELLO WORLD.

In all the above cases, we can see, string literals are concatenated :)

char B[] = "HELLO";
char C[] = " ";
char D[] = "WORLD";
char E[] = B C D;

but same doesn't reflects with variables. why is it so?

Upvotes: 2

Views: 180

Answers (2)

John Bode
John Bode

Reputation: 123588

but same doesn't reflects with variables. why is it so?

Several reasons:

  1. String concatenation is done by the preprocessor before the source text is parsed (this is possible because string literals have the " delimiter, making them easy to recognize at this level);
  2. There is a well-defined initializer syntax that simply doesn't allow for an initialization like char E[] = B C D;;
  3. Similarly, the expressions B, C, and D are converted to pointer expressions and not treated as arrays of char;

Additionally, not all arrays of char are guaranteed to store strings. And you'd have to set aside storage for the concatenated strings.

What does the standard say about it?

C programs are translated in 8 distinct stages (see section 5.1.1.2 of the C 2011 Standard for details).

Stages 1 through 6 describe the actions of the preprocessor; physical source file characters are mapped onto the source character set, trigraphs are converted to single-character equivalents, physical lines with trailing \ characters are spliced into single logical source lines, comments are replaced with a single whitespace character, macros are expanded, preprocessing directives are executed, and, as the last step of the preprocessor, string literals are concatenated.

Stage 7 is where the massaged source text is actually parsed by the compiler.

Stage 8 is basically the linker step.

TL/DR

String literals are special, and are treated specially by the preprocessor.

Upvotes: 1

orlp
orlp

Reputation: 117846

Neither macros nor initializer lists are responsible for what you're observing.

When C finds two literals adjacent to each other in the source code it concatenates them. So "hello" "world" is the same as typing "helloworld".

Upvotes: 1

Related Questions