4
Seeing this, it intrigues because it needs those parentheses that seem unnecessary. What is their functionality?
#define SUB(x, y) ((x) * (y))
4
Seeing this, it intrigues because it needs those parentheses that seem unnecessary. What is their functionality?
#define SUB(x, y) ((x) * (y))
5
Because macro is only a substitution of texts, it is not a construction of the language that considers the semantics of the code, without the parentheses the argument can be confused with the expression. Behold
#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));
}
Behold working in the ideone. And in the repl it.. Also put on the 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 mix everything because in fact it is like this:
4 - 4 * 2
For a better view:
4 - (4 * 2) => 4 - 8 => -4
But the right thing is:
(4 - 4) * (2) => 0 * 2 => 0
Browser other questions tagged c c++ encoding-style macro
You are not signed in. Login or sign up in order to post.