Is there a good reason for always enclosing a define in parentheses in C?
Sometimes you have to write code not with the current caveats in mind, but with the ones of 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 in a hurry. The parentheses are there to remind people to put any modifications within them.
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. Redundancy is for maintainability and composability of future editings.
Yes. The preprocessor concatenation operator (##
) will cause issues, for example:
#define _add_penguin(a) penguin ## a
#define add_penguin(a) _add_penguin(a)
#define WIDTH (100)
#define HEIGHT 200
add_penguin(HEIGHT) // expands to penguin200
add_penguin(WIDTH) // error, cannot concatenate penguin and (100)
Same for stringization (#
). Clearly this is a corner case and probably doesn't matter considering how WIDTH
will presumably be used. Still, it is something to keep in mind about the preprocessor.
(The reason why adding the second penguin fails is a subtle detail of the preprocessing rules in C99 - iirc it fails because concatenating to two non-placeholder preprocessing tokens must always result in a single preprocessing token - but this is irrelevant, even if the concatenation was allowed it would still give a different result than the unbracketed #define
!).
All other responses are correct only insofar that it doesn't matter from the point of view of the C++ scanner because, indeed, a number is atomic. However, to my reading of the question there is no sign that only cases with no further preprocessor expansion should be considered, so the other responses are, even though I totally agree with the advice contained therein, wrong.