When would you use a macro instead of an inline function?
0 upvotes
Practice with AISoon
Prefer static inline functions for most cases — they provide type checking, evaluate arguments once, and are debuggable. Use macros only when you need something inline functions cannot do:
- Type-generic operations — a single
MAXmacro works withint,float,uint32_twithout overloading (C has no function overloading). - Stringification and token pasting —
#and##operators for generating code, enum-to-string tables (X-macros), or logging with__FILE__and__LINE__. - Compile-time constants —
#define ARRAY_SIZE 64for array dimensions (can't use a variable for static array sizes in C89). - Conditional compilation —
#ifdef,#ifndef, include guards.
MISRA C Rule 4.9 advises: use inline functions instead of function-like macros wherever possible.
Source: C / C++ Concepts Q&A
