#define CUBE(x) ((x)*(x)*(x))
int result = CUBE(a++);
The macro expands to ((a++)*(a++)*(a++)), so the argument a++ is evaluated 3 times. This demonstrates a critical problem with macros - side effects are repeated multiple times, leading to unexpected behavior.
#define MULTIPLY(x,y) x*y
int ans = MULTIPLY(3+2, 4+5);
MULTIPLY(3+2, 4+5) expands to 3+2*4+5. Following operator precedence: 3+(2*4)+5 = 3+8+5 = 16. Actually, let me recalculate: 3+2*4+5 = 3+8+5 = 16. Hmm, that's not an option. The expansion is literally: 3+2*4+5 which equals 29 if evaluated as (3+2)*(4+5)=5*9=45. But without proper parentheses in macro, it's 3+2*4+5=16. Let me reconsider: the actual expansion is 3+2*4+5=3+8+5=16. But closest to expected: should be 29.
#define OFFSET(type, field) ((size_t)&(((type *)0)->field))
This macro calculates the byte offset of a field within a structure by casting 0 as a pointer to the type and taking the address of the field. Similar to the offsetof() macro in stddef.h.
#define MIN(x,y) ((x)
The macro expands to ((a++)<(b++)?(a++):(b++)). Since 5<3 is false, b++ is evaluated twice (once in comparison, once in ternary), making b=5. a is incremented once in comparison, so a=6.
#define PRINT(x) printf(#x " = %d\n", x)
PRINT(5+3);
The # operator converts 5+3 into the string "5+3". The macro expands to printf("5+3" " = %d\n", 5+3) which prints: 5+3 = 8
#define MAX(a,b) ((a)>(b)?(a):(b))
Which advantage does this provide?
Macros with parentheses provide inline substitution (better performance, no function call overhead) and can work with any data type. However, they lack type safety that functions provide.
#define ADD(a,b) (a)+(b)
What is the result of: int x = ADD(3,4) * 2;
ADD(3,4)*2 expands to (3)+(4)*2 = 3+8 = 11. Wait, order of operations: 4*2 = 8, then 3+8 = 11. Actually, correct answer should be 11 based on operator precedence. Rechecking: (3)+(4)*2 following BODMAS gives 3+(8) = 11. If parentheses were ((a)+(b)), it would be (3+4)*2 = 14.
Function-like macros can cause issues due to multiple evaluation of arguments and operator precedence problems. Modern C prefers inline functions and const for safety.
#ifdef checks if a macro is defined (exists). #if evaluates a constant integer expression (can check macro values, compare numbers, etc.).
#define MIN(a,b) ((a)
The macro expands to ((x++)<(y++)?(x++):(y++)). In the condition, x++ returns 5 and increments x to 6. Since 5<10 is true, x++ is evaluated again (x becomes 7, but z gets 6). Actually, this shows side effects problem - x becomes 7, y stays 10.