//a macro with parameters: the arguments are pasted into the text,
//every parameter and the whole result go in parentheses
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
int square1 = SQUARE(5);
//square1 is 25
int square2 = SQUARE(2 + 3);
//square2 is 25
double maxValue = MAX(2.5, 1.5);
//maxValue is 2.5
//without parentheses: 2 + 3 * 2 + 3
#define BAD_SQUARE(x) x * x
int square3 = BAD_SQUARE(2 + 3);
//square3 is 11
//an argument is pasted as many times as the parameter is used:
//here i++ runs twice
int i = 5;
int maxI = MAX(i++, 0);
//maxI is 6, i is 7
//several statements go in do { ... } while (0),
//so that the macro works as one statement after if
#define SWAP(a, b) do { typeof(a) tmp = (a); (a) = (b); (b) = tmp; } while (0)
int x = 1;
int y = 2;
if (x < y)
SWAP(x, y);
//x is 2, y is 1
//where a macro is not needed, a function is safer:
//the argument is computed once and its type is checked
int squareInt(int n) {
return n * n;
}
int j = 7;
int square4 = squareInt(j++);
//square4 is 49, j is 8
printf("square1 is %d\n", square1);
printf("square2 is %d\n", square2);
printf("maxValue is %g\n", maxValue);
printf("square3 is %d\n", square3);
printf("maxI is %d\n", maxI);
printf("i is %d\n", i);
printf("x is %d\n", x);
printf("y is %d\n", y);
printf("square4 is %d\n", square4);
printf("j is %d\n", j);