is this legal?

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 :)
or why it is not legal..
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
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.
ok thanks a lot guys
Topic archived. No new replies allowed.