Or even an inline function right? I dont use either of these constructs often at all--what is the difference between an inline function and a "function-like" macro?
Well, one potential problem is that inline was not standard until C99. This isn't necessarily a large problem because many compilers have provided it as an extension for a long time.
There are some things a macro can do that a function can't. Some people like to set pointers to NULL after freeing them, and so a wrapper macro can be used:
Code:
#define xfree(ptr) do { free(ptr); ptr = NULL; } while(0)
You can't define a function to do this, because of type issues. You'd need a function for each pointer type, and moreover, it'd have to take a pointer to pointer as the argument so it could actually set the original pointer to NULL.
For debugging, macros are useful because if you use __FILE__ and __LINE__, they'll be referring to the proper place. As a quick and dirty exapmle:
Code:
#include <stdio.h>
#include <stdarg.h>
#define DBG(fmt, ...) fprintf(stderr, "%s:%d: " fmt, __FILE__, __LINE__, __VA_ARGS__)
static inline void dbg(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "%s:%d: ", __FILE__, __LINE__);
vfprintf(stderr, fmt, ap);
va_end(ap);
}
int main(void)
{
DBG("Error %d\n", 1);
dbg("Error %d\n", 1);
return 0;
}
As a C programmer, I've had macros pounded into my head for years. But I've been coming around to inline functions and am using them a lot more now. If it can be done with an inline function, I use an inline function. I reserve macros for what I believe is their rightful place: only when there is no other option. I know they have their uses, but not as many as I used to use them for.
Functions look a whole lot nicer than multiline macros, anyway.