0

Why does the code snippet 1 works but NOT code snippet 2

Code Snippet 1:

#define mkstr(x) #x

int main(void)
{
    printf(mkstr(abc));

    return (0);
}

Code Snippet 2:

int main(void)
{
    printf(#abc);

    return(0);
}
Erik A
  • 31,639
  • 12
  • 42
  • 67
SRIKANTH
  • 65
  • 7

2 Answers2

2

The first snippet works because it has a function-like macro defined in which you put anything, the value is correctly assigned as a constant.

OTOH, the second one has a syntactic error because the compiler doesn't expects that parameter passed in printf(). Thus, the # is meaningless there.

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • You could leave the C++ tag, but I can't argue with your edit, C and C++ are different languages and the separation is encouraged, like @klutt stated int the accepted answer. – anastaciu Aug 08 '20 at 09:42
  • @anastaciu the question is explicitly asked for C. That's why I had removed C++ tag and nothing. If you see something irrelevant in the edit, then you can take it back. No problem at all. – Rohan Bari Aug 08 '20 at 10:14
  • 1
    No, I think it's ok. – anastaciu Aug 08 '20 at 10:15
1

Commands starting with the # symbol are called Macros in C and C++. Macros are blocks of code that are named and referenced with that name.

There are 2 popular types of macros - the Object-like and the function-like. The one you're using is the function-like macro.

The Preprocessor is responsible for replacing macro calls with the actual object/function calls.

The statement in Snippet 1

#define mkstr(x) #x

The above macro uses a special feature called the stringizing. The # before the x specifies that the input parameter should be treated as is, ie. converted to a string constant, thereby returning a string equivalent of what is passed.

On the contrary, when you call the below code in Snippet 2

printf(#abc);

doesn't mean anything. It's a compiler error as #s are not allowed in the middle or end of a statement (please not that # is allowed to be part of string such as "#1", or when used as a character literal as '#'). And thus any statement that starts with # becomes a macro.

Caution: Use of macros is discouraged. You can refer this answer on StackOverflow on why not to use them.

Refer the below resources to learn more about macros

Debargha Roy
  • 2,320
  • 1
  • 15
  • 34