Recently, an answer of Peter Taylor here says:
To get a macro equivalent to
f(n){n=n?:1;}
you need
-Df(n)=((n)?:1)
which is longer, so there's no point.
So are those criteria really necessary? Which of the following criteria should be satisfied:
- Arguments must be put in parentheses.
- The function itself must be wrapped in parentheses (unless it's single token).
- The argument must be referenced exactly once.
- There should be a trailing newline (if use
#define
) (because you can't put the code right after the macro, you need a trailing newline). - If there are multiple statements there should be
if(1){...}else
wrap ordo{...}while(0)
wrap.
Real world macros satisfy all three of them (except some nonstandard ones (never used in production code), for example the macro defined by
#define all(x) begin(x), end(x)
. With this you can do some (weird?) trick such as
sort(all(x))
, which avoid duplication of x
in code - source: this or this)
Should that be enforced?
- Agree: That's the standard of C macro.
- Agree: That makes the macro more like a real "function".
- Disagree: That may change a lot of existing submissions.
- Disagree: Even without that condition, we can call it with variables, and wrap the return value in parentheses. This is "require more input than necessary".
- Disagree: That takes more bytes. (← should not be a problem)