why macro not expanded ?

J

junky_fellow

Consider the following piece of code:
$ cat a.c
extern int func(int);
#define func(i) (i+i)
int main(void)
{
(func)(10);
}

On preprocessing the above code,
$ cc -E a.c
# 1 "a.c"
extern int func(int);

main()
{
(func)(10);
}
 
R

RAJU

Here there is a problem in code. First of all we need to understand
what a macro is.
#define name replacment_text

The name can have argumants also.

In this code. func(x) will be replaced by (x+x). But, you have used
(func)and it will be treated as a function call. You have provided a
declaration (extern int func(int);) for that function. So, it's
assuming that (func) is a function.

If you are expecting a macro to be used then
(func(10)) (10); to be used in your code. This will result (10+10) (10)
after preprocessing and which is syntactically incorrect.

(func(10))*(10); will give you the expected result.

Regards,
Raju
 
L

Lawrence Kirby

Consider the following piece of code:
$ cat a.c
extern int func(int);
#define func(i) (i+i)

For this to be safe (well safer anyway) you should enclose the arguments
in parentheses as in

#define func(i) ((i)+(i))
int main(void)
{
(func)(10);
}
}
On preprocessing the above code,
$ cc -E a.c
# 1 "a.c"
extern int func(int);

main()
{
(func)(10);
}
}
------------------------------------------------------------- func being
a macro,(func)(10) should be expanded to (10+10)(10), but it doesn't
seem to. It is treated as a function. Why is it so ?

A function like macro is only expanded when the ( directly follows the
function name (intervening white-space is allowed). In your example
(func)(10) there is a ) between the name and the ( so it is not expanded.
Using parentheses around the name like this is a recognised method of
forcing a function call rather than a macro expansion. Of course it only
works with function-like macros.

Lawrence
 
C

Chen Ming

becase of the bracket indicate the *func* as a function.

Consider the following piece of code:
$ cat a.c
extern int func(int);
#define func(i) (i+i)
int main(void)
{
(func)(10);
}

On preprocessing the above code,
$ cc -E a.c
# 1 "a.c"
extern int func(int);

main()
{
(func)(10);
^^^^^^^
you can replace *(func)* with *func*, then u will get what you want.
 

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

Forum statistics

Threads
474,169
Messages
2,570,915
Members
47,456
Latest member
JavierWalp

Latest Threads

Top