1
$\begingroup$

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?

$\endgroup$

3 Answers 3

1
$\begingroup$

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.

$\endgroup$
1
  • $\begingroup$ This is essentially what I wanted to know. $\endgroup$
    – user7988
    Commented Oct 19, 2018 at 22:46
4
$\begingroup$

#define PLUS +

3 PLUS 5

Any more questions?

$\endgroup$
2
  • $\begingroup$ Is there a situation in which this would be a practical solution to a problem? $\endgroup$
    – user7988
    Commented Oct 18, 2018 at 22:21
  • $\begingroup$ 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. $\endgroup$ Commented Oct 18, 2018 at 22:36
2
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.