Clearly, there are times where #define statements must have parentheses, like so:
#define WIDTH 80+20
int a = WIDTH * 2; // expect a==200 but a==120
So I always parenthesize, even when 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?
Yes. The preprocessor concatenation operator (
##) will cause issues, for example:Same for stringization (
#). Clearly this is a corner case and probably doesn’t matter considering howWIDTHwill 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.