SRIKANTH
SRIKANTH

Reputation: 85

Operator to convert to string

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);
}

Upvotes: 0

Views: 315

Answers (2)

Debargha Roy
Debargha Roy

Reputation: 2698

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

Upvotes: 1

Rohan Bari
Rohan Bari

Reputation: 7726

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.

Upvotes: 2

Related Questions