tags:

views:

123

answers:

4

Hello,

I am wondering if macro definitions can contain space. Let's take for example this code:

#define MACRO_PARAM int param2

int function(int param1, MACRO_PARAM)
{
    return param1+param2;
}

This works ok with Visual Studio 8 and gcc 3.4.5 (mingw). For me this is good enough for the moment but is this standard? or can I rely on this behavior across different compilers?

Thanks,

Iulian

PS: To answer to the question why would you wanna do that?: I'm using bison flex for a project and I'm trying to make something reentrant (I need to declare some macros for function parameters).

+4  A: 

You'll need to end each line of the definition with a \ (except the last).

Brian Hooper
In my case the definition has only 1 line I believe it is ok.
Iulian Şerbănoiu
I will select this answer because it provides additional info. Thanks
Iulian Şerbănoiu
+2  A: 

Yes, you can do that.

Daniel Daranas
Is this part of the (standard) documentation?
Iulian Şerbănoiu
@Iulian: A space is a very common character. I don't know if the C and the C++ standards explicitly say that "preprocessor macros can contain spaces", but that would be a bit like saying "function names can contain the letter 'z'".
Daniel Daranas
+1 I believe it is a good way of thinking (what's not explicitly forbidden is allowed :) )
Iulian Şerbănoiu
@Iulian: According to standard 2.4/2 (lex.pptoken), "Preprocessing tokens can be separated by white space; this consists of comments, or white-space characters". So space is okay in macro replacement-list.
czchen
@czchen: Great clarification. Are you quoting the C or the C++ standard?
Daniel Daranas
+2  A: 

Yes, you can rely on this behaviour.

Polybos
+2  A: 

Yes, you can certainly have multi word (indeed, multi-line) expansions to preprocessor macros, in any remotely-conformant compiler. C macros are pretty nasty, but if they couldn't even do that, they'd be largely useless.

The preprocessor syntax can do quite a lot (enough that it's easily abused). See section 6.10.3 of the standard, ISO-9899 (PDF), if you want or need legalistic chapter and verse.

Norman Gray
+1 @Norman Gray: Thanks! I now see it clearly what do you mean by abuse :) - I'm diving into the bison generated code. Didn't have any problems with flex as it worked quite well without doing much voodoo. But with bison I believe I unleashed the evil god of macros.
Iulian Şerbănoiu