views:

172

answers:

4
#include<stdio.h>
#include<conio.h>
#define ABC 20
#define XYZ 10
#define XXX ABC - XYZ

void main()
{
    int     a;

    a = XXX * 10;

    printf("\n %d \n", a);

    getch();
}

I thought the output should be 100 but when i saw the result i found o/p as -80. when i put bracket as #define XXX (ABC-XYZ) then i get output as 100 but without bracket i get o/p as -80.

+3  A: 
a = XXX * 10;

will change to the following before compilation:

a = 20 - 10 * 10;

which evaluates to -80

codaddict
+13  A: 

The preprocessor is a dumb beast. It works on a purely textual level, without regard for what it's doing to the code semantically. Let's see what it does in this case:

a = XXX * 10;

becomes

a = ABC - XYZ * 10;

which becomes

a = 20 - 10 * 10;

which is, obviously, -80.

What was probably intended was

#define XXX (ABC - XYZ)

This is one reason why macros are considered evil.

Thomas
Oh thanks it was so easy and i was so confused. I think my brain is not working now a days. :)
Abhi
+2  A: 

It is calculating like this ,

20-10*10

Use braces in the macro XXX.

#define XXX (ABC-XYZ)
karthi_ms
+2  A: 

Here XXX is replaced by ABC-XYZ So it is look like the follow

20 - 10 * 10

So the output is -80

muruga