Home > Software engineering >  C code doesn't give expected answer when using macros for multiplication and addition
C code doesn't give expected answer when using macros for multiplication and addition

Time:09-28

 #include <stdio.h>
#define sum(x,y) x y
#define f(x,y) sum(x,y)*2
int main(int argc, char *argv[])
{
    float m=6,n=1;
    int x= f(m,n);
    printf("x is %d\n",x);  
}

I get the answer for x as 8.How is this possible.

CodePudding user response:

The macros would resolve to 6 1 * 2. Macros are a direct text replacement mechanism.

First the compiler would do sum(x,y)*2 and then x y*2.

Macros are not functions but direct text replacements. If you add a lot of brackets everything will be fine regardless of how/what you substitute with the macro.

#define sum(x,y) ((x) (y))

CodePudding user response:

I find it helpful to look at the code after it's being expanded by the macro processor. With gcc it would cpp your_file.c:

...

int main(int argc, char *argv[])
{
    float m=6,n=1;
    int x= m n*2;
    printf("x is %d\n",x);
}

So your macro should be:

#define sum(x,y) (x y)

or even better:

#define sum(x,y) ((x) (y))
  • Related