Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why pre-processor gives a space?

I want to comment a line using the pre-processor:

#define open /##*

#define close */

main()
{
        open commented line close
}

when I do $gcc -E filename.c I expected

/* commented line */ 

but I got

/ * commented line */ 

so that the compiler shows an error

Why it is giving an unwanted space ?

like image 714
abubacker Avatar asked Mar 06 '10 07:03

abubacker


2 Answers

From the GNU C Preprocessor documentation:

However, two tokens that don't together form a valid token cannot be pasted together. For example, you cannot concatenate x with + in either order. If you try, the preprocessor issues a warning and emits the two tokens. Whether it puts white space between the tokens is undefined. It is common to find unnecessary uses of '##' in complex macros. If you get this warning, it is likely that you can simply remove the '##'.

In this case '*' and '/' do not form a valid C or C++ token. So they are emitted with a space between them.

(Aside: you are likely to get C compilation errors even if you do manage to insert "comments" into the output of the C preprocessor. There aren't supposed to be any comments there.)

like image 53
Stephen C Avatar answered Sep 24 '22 15:09

Stephen C


The error is because /* is not a valid token.

As explained from the CPP doc:

two tokens that don't together form a valid token cannot be pasted together. For example, you cannot concatenate x with + in either order.

You can get the error by pasting other nonsense stuff e.g. /##+ or +##-.


About the space, it is deliberately inserted to avoid creating a comment and mess up the rest. From the GCC source code:

    /* Avoid comment headers, since they are still processed in stage 3.
         It is simpler to insert a space here, rather than modifying the
         lexer to ignore comments in some circumstances.  Simply returning
         false doesn't work, since we want to clear the PASTE_LEFT flag.  */
      if ((*plhs)->type == CPP_DIV && rhs->type != CPP_EQ)
        *end++ = ' ';
like image 29
kennytm Avatar answered Sep 23 '22 15:09

kennytm