is this legal?

Apr 22, 2010 at 8:47am
hello guys, can someone tell me why is this legal...

extern int neg(int x);
#define neg(x) (-x)
...

y = neg(i+j);
-----------

actually this is a hw question.. and i have no idea if it's legal or not.
Help if you can, thanks much :)
Apr 22, 2010 at 8:48am
or why it is not legal..
Apr 22, 2010 at 11:32am
All I will say that the function neg will never be called.
Only the macro will be invoked because it is defined right after the prototype.

Oh, btw, try compiling that piece of code and you'll know of a slight C macro related problem.
The result of i+j will be completely different from what you might expect.

Try compiling this:

1
2
3
4
5
6
7
8
9
10
11
12
#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif
#define neg(x) (-x)
int main (int argc, char **argv) {
    int x = 5, y = 5;

    printf ("neg(x+y) = %d;\n", neg(x+y));
    return 0;
}


What do you expect the result to be, -10? Of course 5+5 = 10; neg (10) = -10.
That should tell you what the problem is and what is actually wrong in the neg macro...
It can be easily solved though. (I won't tell you how, not yet).
This is partly why macros are discouraged.
Last edited on Apr 22, 2010 at 11:49am
Apr 22, 2010 at 1:15pm
Yes... but, it is legal.
It is just really, really stupid.

It would not be legal if the #define was before the function prototype.

Hope this helps.
Apr 22, 2010 at 3:48pm
ok thanks a lot guys
Topic archived. No new replies allowed.