Here's a list of things to watch out for when using macros.
#define CUBE(i) (i * i * i)
CUBE(2++) evaluates to (2 * 3 * 4)
Instead, use an inline function to protect yourself from misusing the macro:
inline int cube(int i) {
return i * i * i;
}
#define BUMP (count++)
int count;
main() {
int count = 0;
BUMP;
}
This increases the count variable in main's scope instead of the global count variable. You should never use the same variable name in subscopes, they're confusing.
Use an inline funtion to protect itself from the scope of the calling function.
inline void BUMP() {
count++;
}
You'll never know what people will pass to your macro, so you need to make sure order of operations don't cause unexpected results
#define CUBE(i) (i * i * i)
CUBE(2+1) -> (2 + 1 * 2 + 1 * 2 + 1) = 7
#define CUBE(i) ((i) * (i) * (i))