mike fisher
mike fisher

Reputation: 139

macro definition function

#include <stdio.h>

#define next(x) x + 1
#define prev(x) x - 1
#define mult(x,y) x * y

int main(void) {

int a = 3, b = 4;
printf("%d\n", mult(next(a), prev(b)));
return 0;

}

mult(next(3),prev(4)) expands to mult(3+1, 4-1) which is 12. But the answer is 6.

Why is that?

Upvotes: 2

Views: 113

Answers (1)

pmg
pmg

Reputation: 108988

... and mult(3+1, 4-1) expands to

3+1 * 4-1

which results in 3 + 4 - 1 or 6.

In a function like macro definition put parenthesis around each and every parameter and around the whole definition

#define next(x) ((x) + 1)
#define prev(x) ((x) - 1)
#define mult(x, y) ((x) * (y))

Upvotes: 10

Related Questions