I have been trying to understand macro expansion and found out that the second printf gives out an error. I am expecting the second print statement to generate the same output as the first one. I know there are functions to do string concatenation. I am finding it difficult to understand why first print statement works and the second doesn't.
#define CAT(str1, str2) str1 str2
void main()
{
char *string_1 = "s1", *string_2 = "s2";
printf(CAT("s1", "s2"));
printf(CAT(string_1, string_2));
}
Concatenating string literals, like "s1" "s2"
, is part of the language specification. Just placing two variables next to each other, like string_1 string_2
is not part of the language.
If you want to concatenate two string variables, consider using strcat
instead, but remember to allocate enough space for the destination string.
Try to do the preprocessing "by hand":
CAT
is supposed to take 2 input variables, and print them one after the other, with a space between. So... if we preprocess your code, it becomes:
void main()
{
char *string_1 = "s1", *string_2 = "s2";
printf("s1" "s2");
printf(string_1 string_2);
}
While "s1" "s2"
is automatically concatenated to "s1s2"
by the compiler, string_1 string_2
is invalid syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With