Why have so many parentheses in macro?

5

Seeing this intrigues you because you need those parentheses that seem unnecessary. What is their functionality?

#define SUB(x, y) ((x) * (y))
    
asked by anonymous 23.03.2017 / 11:37

1 answer

5

Because macro is only a replacement of texts, it is not a construction of the language that considers the semantics of the code, without the parenthesis the argument can be confused with the expression. See

#include <stdio.h>
#define SUB_UNSAFE(x, y) x * y
#define SUB(x, y) ((x) * (y))

int main(void) {
    printf("%d\n", SUB_UNSAFE(4 - 4, 2));
    printf("%d\n", SUB(4 - 4, 2));
}

See running on ideone . And on the Coding Ground (with problems now). Also put it on GitHub for future reference .

You can see that if the parentheses have situation that the calculation is done wrong because the precedence in the expression is confused with the argument and mixes everything because it actually looks like this:

4 - 4 * 2

For a better view:

4 - (4 * 2) => 4 - 8 => -4

But the correct one is:

(4 - 4) * (2) => 0 * 2 => 0
    
23.03.2017 / 11:37