Reputation: 1254
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
Reputation: 123588
but same doesn't reflects with variables. why is it so?
Several reasons:
"
delimiter, making them easy to recognize at this level);char E[] = B C D;
;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
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