Pros and Cons of Different macro function / inline methods in C
Posted
by Robert S. Barnes
on Stack Overflow
See other posts from Stack Overflow
or by Robert S. Barnes
Published on 2009-10-15T10:01:34Z
Indexed on
2010/03/31
3:43 UTC
Read the original article
Hit count: 283
According to the C FAQ, there are basically 3 practical methods for "inlining" code in C:
#define MACRO(arg1, arg2) do { \
/* declarations */ \
stmt1; \
stmt2; \
/* ... */ \
} while(0) /* (no trailing ; ) */
or
#define FUNC(arg1, arg2) (expr1, expr2, expr3)
To clarify this one, the arguments are used in the expressions, and the comma operator returns the value of the last expression.
or
using the inline
declaration which is supported as an extension to gcc and in the c99 standard.
The do { ... } while (0)
method is widely used in the Linux kernel, but I haven't encountered the other two methods very often if at all.
I'm referring specifically to multi-statement "functions", not single statement ones like MAX or MIN.
What are the pros and cons of each method, and why would you choose one over the other in various situations?
© Stack Overflow or respective owner