Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why stringizing operator is only accepted as a macro?

I tried to use the # operator in my code:

#include <stdio.h>

int main(void)
{
    printf("hello %s !!! n", #world);
    return 0;
}

Compiled with gcc, this codes gives the following error:

str.c: In function ‘main’:
str.c:5:27: error: stray ‘#’ in program
  printf("hello %s !!! n", #world);

But, when I define a macro that uses this operator, the code is compiled:

#include <stdio.h>

#define STRINGIFY(x) #x

int main(void)
{
    printf("hello %s \n", STRINGIFY(world));
    return 0;
}

Is this error reported by the pre-processor? If so, why?

like image 752
J.W Avatar asked Apr 11 '19 15:04

J.W


People also ask

What is Stringizing operator in C?

The number-sign or "stringizing" operator (#) converts macro parameters to string literals without expanding the parameter definition. It's used only with macros that take arguments.

What is the purpose of the operator in a macro definition?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.

What is a macro in C++?

Macros and its types in C/C++ A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro.

Can macros use other macros in C?

Before reading your question, I thought you were asking whether a macro definition can define another macro, such as #define FOO(x) #define BAR x . The answer to that question (which you didn't actually ask) is no; a macro definition cannot include further preprocessor directives.


1 Answers

Because #parameter is the part of macro expansion. All this is done by a preprocessor before the compiler even sees the code. And this token is applied to macro parameters only. Consider the following macro:

#define STR(x) #x

Str(Hello) is "Hello"

But if we write #word in the code the preprocessor does not see this as a part of a macro and word is not a macro parameter. Thus the preprocessor ignores it. The compiler sees the same #word and knows nothing what to do with it. So it reports an error. Consider the following text worked out by a preprocessor.

#define STR(x) #x
const char * str=STR(Hello);
const char * buggy_str=#Hello;

The result will be:

const char * str="Hello";
const char * buggy_str=#Hello;

The C compiler sees the first string and it is ok for him. But when he sees the second string, he knows nothing about the token # and thus reports an error.

like image 169
Alexey Godin Avatar answered Nov 15 '22 04:11

Alexey Godin