0

So I have an exam tomorrow and I encountered this on my questions.

#define mul(x,y) (x * y)
#include <stdio.h>
#include <string.h>

int main()
{
    int x = 3;
    int y = 4;
    int z = 0;
    z = mul(x+1, y+1);
    printf("4 * 5 = %d \n", z);
    return 0;
}

my question is, why is this outputting 8 instead of 20. Because when I replace z= mul(x+1,y+1) with z= mul((x+1),(y+1)) I get the correct answer of 20

Paso
  • 27
  • 5

1 Answers1

3

Macro #define mul(x,y) (x * y) actually tells the pre-compiler that if it finds string mul(any pattern X, any pattern Y), it should replace it with (any pattern X * any pattern Y).

So what do you have in your example?

int x = 3;
int y = 4;
int z = 0;
z = mul(x+1, y+1);

After mul is replaced, you get

int x = 3;
int y = 4;
int z = 0;
z = x+1*y+1;

==> z = 3 + 1*4 + 1 = 8

The best practice is to surround each macro parameter by brackets. In your example (to achieve the desired result) it should be:

#define mul(x,y) ((x) * (y))
Alex Lop.
  • 6,810
  • 1
  • 26
  • 45