Printing space using macro and # operator in C

I worked with macros and wrote one like this:

#define STR(name) #name

      

I meant STR()

scribbling whatever was given to him as an argument and it looks like it worked.

printf( STR(Hello) )

      

gave the result as expected:

Hello

      

So did

printf( STR(Hello world) );
printf( STR(String) STR(ise) );

      

who gave

Hello world
Stringise

      

But when I tried to use STR()

only space to print it just didn't work.

printf( STR(Hello) STR( ) STR(World) ); //There’s a space between the parenthesis of the second STR

      

Output output:

HelloWorld

      

STR( )

Ignored here .

Why is this? Is there a way to use it while keeping the space-only macros as an argument?

I'm just wondering if this is possible.

+3


source to share


1 answer


It is impossible for a building to fit into one space. The semantics of the operator are #

detailed in C11 6.10.3.2p2 :

If the substitution list is immediately preceded by a #

preprocessing token , then both are replaced with a single character-string preprocessor character, which contains the spelling of the preprocessing token sequence for the corresponding argument. Each occurrence of a space between the argument preprocessing tokens becomes a space character in the character string literal. A space before the first preprocessing token and after the last preprocessing token that constitutes this argument is removed. [...] character string literal, the corresponding empty arguments ""

.
...].

Thus, since the space is not a preprocessing token, and the trailing and trailing space is removed, it is not possible for a string operator to create a resulting string literal that contains only one space. As you noticed, STR( )

will pass an empty argument to the macro, and this will bind to ""

; Similarly

STR(     Hello

World
)

      

will be expanded to "Hello World"

; that is, each occurrence of a space will become a single spatial symbol, and the previous and trailing white space will be removed.




However, while it is impossible to create a tiny space, you can achieve the desired result. The preprocessor concatenates sequential string literals into one, so it "Hello" " " "World"

will be converted to "Hello world"; so

printf(STR(Hello) " " STR(World));

      

after expanding macro exchange to

printf("Hello" " " "World");

      

and then -

printf("Hello World");

      

+3


source







All Articles