Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in macro expansion

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));
}
like image 541
Ajit Avatar asked Jan 07 '23 06:01

Ajit


2 Answers

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.

like image 92
Some programmer dude Avatar answered Jan 18 '23 08:01

Some programmer dude


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.

like image 45
Amit Avatar answered Jan 18 '23 07:01

Amit