Clearly, there are times where define
s must have parentheses, like so:
#define WIDTH 80+20
int a = WIDTH * 2; //expect a==200 but a==120
So I have always parenthesized, even if it's just a single number:
#define WIDTH (100)
Someone new to C asked me why I do this, so I tried to find an edge case where the absence of parentheses on a single number define
causes issues, but I can't think of one.
Does such a case exist?
No. There is no case where
#define WIDTH 100
can yield an unambiguous or "surprising" expansion. That's because it can only result in a single token being replaced by a single token.As you know, macro confusion ensues when a single token (e.g.
WIDTH
) results in multiple tokens (e.g.80 + 20
). As far as I can surmise, that's the only cause for the use of parentheses in substitutions and, as explored in my first paragraph, it doesn't apply here.However, this technical fact aside, it may still be a good practice. It promotes habit, and it also serves as a reminder if that macro ever gets modified to something more complex.
There's a good reason, sometimes.
For a single number, there's no good reason.
For other cases, as you have shown yourself, there is a good reason.
Some people prefer to be extra careful, and always use the parentheses (@aix recommends it. I don't, but there's no hard answer).
Whenever the define consists of a single token (one operand only, no operators), the parentheses are not needed because a single token (such as
100
) is an indivisible atom when lexing and parsing.Sometimes you have to write code not with the current caveats in mind, but with the caveats of the next time it is going to be edited.
Right now your macro is a single integer. Imagine someone editing it in the future. Let's say they are not you, but someone who is less careful or in more of a hurry. The parenthesis is there to remind them to put any modifications in parenthesis.
This kind of thinking is a good habit in C. I personally write code in a style which some people might find "redundant", with things like this but especially with regards to error handling. The redundancy is for maintainability and composability of future edits.
Since
100
is a single token, I doubt you'll find a corner case where the parentheses matter (for a single token!)It's still a good habit IMO, since they can matter when there are multiple tokens involved.
When code defines only a number, @Alexander Gessler well answers the question.
Yet many coders do not notice the unary operators in the following:
When code uses a
#define
that employs an operator, enclosing()
insures expected numeric results and precedence.The last line of code may compile given C99 semantic changes @Olaf