- Joined
- Mar 10, 2019
You can, but take careful note of all the seemingly unnecessary parentheses that I added, because they're necessary (if not in this case, in some other cases, so it should be done out of habit).I didn’t know you could use define like that
#define
is a preprocessor directive, and it performs a relatively naive code replacement. It does not evaluate anything. Adding parentheses guarantees that the parameter is atomic and your logic doesn't evaluate to something unexpected.For example, if you were to write
if (numRolls == 1 && WIN_FIRST_ROLL(diceSum))
, the preprocessor would replace that with if (numRolls == 1 && ((diceSum) == 7 || (diceSum) == 11))
. The &&
operator has higher precedence than the ||
operator, which means the outer set of parentheses becomes necessary. If you leave the parentheses off, the &&
would be evaluated first, so the logic would become if ((numRolls == 1 && (diceSum) == 7) || (diceSum) == 11)
.Similarly, it's good practice to be in the habit of writing
(X)
instead of X
, because otherwise you will run into scenarios where you pass something like a + b
and the low-priority +
operator can allow your argument to be split up incorrectly if you don't wrap parentheses around it to guarantee that the argument is evaluated correctly. a + b * c
is not the same as (a + b) * c
.