macros with parameters

S

Serve Laurijssen

The following code compiles on 2 compilers here:

#define X(a) ((a)+10)

int main(void)
{
int X = 2;

return 0;
}

but if X is defined as #define X (2)
then this code doesnt compile anymore?

Is that according to standard ?
 
H

Hallvard B Furuseth

Serve said:
The following code compiles on 2 compilers here:

#define X(a) ((a)+10)

int main(void)
{
int X = 2;

return 0;
}

Yup... the X macro takes one argument, but since you didn't give
an argument it can't be the macro, so it is not expanded.
but if X is defined as #define X (2)
then this code doesnt compile anymore?

With a space after the macro name, it is an "object-like" macro
which does not take any parens. So your code becomes

int (2) = 2;
Is that according to standard ?

Yup.
 
R

Richard Heathfield

Serve Laurijssen said:
The following code compiles on 2 compilers here:

#define X(a) ((a)+10)

int main(void)
{
int X = 2;

return 0;
}

but if X is defined as #define X (2)
then this code doesnt compile anymore?

Is that according to standard ?

Yes. #define X(a) ((a)+10) defines a function-like macro. To invoke a
function-like macro, you'd have to say something like X(arg), complete with
parenthesised argument - not just X on its own. So your example program
simply defines an int called X, which is obviously legal; it doesn't invoke
your macro at all.

#define X (2) doesn't define a function-like macro. If you were to change
your program in this way, it would expand to:

int main(void)
{
int (2) = 2;

return 0;
}

which is obviously illegal.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top