简体   繁体   中英

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?

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

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[] = BCD; ;
  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM