# Is there a reason to NOT wrap preprocessor macros in parens?

I'm writing a design document for a macro expansion language that is specifically intended for arithmetic operations on integers. I've already determined that not wrapping macros with parens can lead to unexpected behavior. Rather than expect users to practice impeccable code hygiene, implementing automatic parens will save the users time and reduce bugs.

If a preprocessor adds enclosing parentheses every time a macro is expanded, is any useful functionality lost?

For integer expressions, auto-wrapping in parentheses seems harmless.

For other macros, though, it would potentially break code. For instance in C, it's fairly common to see function-like macros like this:

#define swap(x,y)       \
do {                 \
int swap_tmp = x;  \
y = x;             \
x = swap_tmp;      \
} while (0)


which would work as a regular statement, e.g.

if (condition)
swap(x,y);
else
swap(y,z);


Adding parentheses around swap(x,y) would break this.

Arguably, these macros are needed since the language has poor features, lacking pass-by-reference, or perhaps because the programmer wants to be sure the function is inlined for some reason. Still, they are used.

• This is essentially what I wanted to know. – Jack Stout Oct 19 '18 at 22:46

#define PLUS +

3 PLUS 5

Any more questions?

• Is there a situation in which this would be a practical solution to a problem? – Jack Stout Oct 18 '18 at 22:21
• No idea. But if this is going to turn into a discussion of whether some given lost functionality is "useful", then this isn't really a Stack-Exchange-appropriate question. – David Richerby Oct 18 '18 at 22:36

You can think of the C preprocessor as a machine that operates on lexical tokens. All of the fancy operations that it can do (e.g. string pasting, converting identifiers to strings) operate on tokens and produce tokens.

Compare this with, say, the Lisp macro system, which rewrites a tree into a tree.

Decide on the model of the macro system first. That should guide your thinking.