4

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));
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ajit
  • 261
  • 3
  • 15

2 Answers2

8

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.

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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.

Amit
  • 45,440
  • 9
  • 78
  • 110
  • I thought it would be the same as the first statement as the value in string_1 is "s1" and string_2 is "s2" – Ajit Nov 02 '15 at 12:44
  • All the preprocessor does is manipulate the source code itself, once that's done, the code goes through normal compilation, and must be valid for that purpose. As I explained, `string_1 string_2` is invalid, and can't compile. – Amit Nov 02 '15 at 12:46
  • @Pete `string_1` is a variable to be precise , and `"s1"` is a string literal . Both are treated in different manner . – ameyCU Nov 02 '15 at 12:46
  • @Pete `string_1` doen's have the value "s1". It's a pointer that points to a zero terminated string "s1". – Jabberwocky Nov 02 '15 at 12:47