Are there any significant benefits to using macros instead of static inline methods?
Macros do not do type-checking, and do not evaluate their arguments, which brings great power and great danger.
So (to quote a well known example)
#define MAX(a,b) (a>b)?a:b
might seem like a better idea than
static inline int max(a,b) { return (a>b)?a:b; }
as it doesn't require an int
argument (i.e. will work for all types that support the >
operator), save for the fact that
- It evaluates
a
or b
twice (consider MAX(a++,b++)
)
- It has the potential for operator precedence issues
This solves the second:
#define MAX(a,b) ((a)>(b)?(a):(b))
How can one implement passing of varargs further down the call chain with static inline method which can be done in one step with a macro?
C99 supports variadic macros, and gcc
has (non-standard) extensions to this defined here.
In fact there are two formats:
#define debug(format, ...) fprintf (stderr, format, __VA_ARGS__)
where __VA_ARGS__
gets replaced by the variadic elements; this is standard C99.
gcc
also provides:
#define debug(format, args...) fprintf (stderr, format, args)
where args
can represent more than one argument.
In the first formulation, with gcc
only, you can cope with the arguments being omitted completely and avoid a superfluous comma using the pasting macro operator ##
, i.e.:
#define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)
There is no standards-based way of achieving that.
[Does the] compiler [always] inline static inline
methods?
No, the compiler is free to do what it wants. It can inline them, or produce one set of object code per compilation unit. However, at least in theory, it could do the same with #define
'd macros. The compiler will not always convert multiple levels of inline macros into a single expression, as even a single inline macro may not in fact be coded inline; normally the compiler is smarter than the programmer in determining whether that is a good idea or not.