Re: [PATCH] Documentation: Explain a second alternative for multi-line macros.



On Sun, Dec 31, 2006 at 02:32:25PM -0500, Robert P. J. Day wrote:

Generally, inline functions are preferable to macros resembling
functions.

This should be stressed, IMHO. We have too many macros which have no
reason to live.

-Macros with multiple statements should be enclosed in a do - while block:
+There are two techniques for defining macros that contain multiple
+statements.

-#define macrofun(a, b, c) \
- do { \
+ (a) Enclose those statements in a do - while block:
+
+ #define macrofun(a, b, c) \
+ do { \
+ if (a == 5) \
+ do_this(b, c); \
+ } while (0)
+
+ (b) Use the gcc extension that a compound statement enclosed in
+ parentheses represents an expression:
+
+ #define macrofun(a, b, c) ({ \
if (a == 5) \
do_this(b, c); \
- } while (0)
+ })

When giving two alternatives, the reader will thank you if you explain
when each should be used. In this case, the second form should be used
when the macro needs to return a value (and you can't use an inline
function for whatever reason), whereas the first form should be used
at all other times.

Cheers,
Muli
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/



Relevant Pages

  • Re: [PATCH] Documentation: Explain a second alternative for multi-line macros.
    ... On Sun, 31 Dec 2006, Muli Ben-Yehuda wrote: ... We have too many macros which have no ... In this case, the second form ... use an inline function for whatever reason), ...
    (Linux-Kernel)
  • Re: mixed mode allowed for comparison macros?
    ... >> I don't see any reason it wouldn't be, why do you think it might not ... > Furthermore I have empirical evidence that prominent C committee members ... the whole point of the macros is to be able to perform ... non-exceptional comparision on real floating-point types. ...
    (comp.std.c)
  • Re: [PATCH] Fix dirty page accounting in redirty_page_for_writepage()
    ... Patches would have to be redone against whatever API we agree on. ... They are macros and may do weird things with the variables. ... The reason not to use the percpu_* names was that they were x86 arch ...
    (Linux-Kernel)
  • Re: Python syntax in Lisp and Scheme
    ... If I call a method and pass it a function object, ... > (three functions, or macros, that start, run, and stop the reactor), ... > reason about, compared to something that has the potential to dissect ... Given that I've seen nobody say, for days!, ...
    (comp.lang.python)
  • Re: Why not FILE instead of FILE*?
    ... >>Not bad for a simple minded optimizer. ... There is a reason C is ... What is potentially dangerous in macros like getc and putc? ... Dan Pop ...
    (comp.lang.c)