Search code examples
cc-preprocessoroperator-precedenceside-effects

Why the output for "a" is -80?


#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 output as -80. When I put brackets as #define XXX (ABC-XYZ) then I get output as 100 but without brackets I get output as -80.


Solution

  • 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.