Exercise: Create Safe Macros

Write code to solve the problem.

Question

Macros can simplify repeated computations, but they must be written carefully to avoid unexpected behavior.

Your task is to define two macros:

  1. SQUARE(x): Returns the square of a number.

  2. MAX(a, b): Returns the larger of two values.

These macros must work correctly even when expressions are passed as arguments.

Expected output:

Square of 3 is 9
Max of 3 and 5 is 5
Square of (a + 1) is 16
Max of (a + 2) and (b - 1) is 5

Exercise: Create Safe Macros

Write code to solve the problem.

Question

Macros can simplify repeated computations, but they must be written carefully to avoid unexpected behavior.

Your task is to define two macros:

  1. SQUARE(x): Returns the square of a number.

  2. MAX(a, b): Returns the larger of two values.

These macros must work correctly even when expressions are passed as arguments.

Expected output:

Square of 3 is 9
Max of 3 and 5 is 5
Square of (a + 1) is 16
Max of (a + 2) and (b - 1) is 5
C
#include <stdio.h>
/* Define your macros here */
int main() {
int a = 3;
int b = 5;
printf("Square of %d is %d\n", a, SQUARE(a));
printf("Max of %d and %d is %d\n", a, b, MAX(a, b));
/* Test with expressions */
printf("Square of (a + 1) is %d\n", SQUARE(a + 1));
printf("Max of (a + 2) and (b - 1) is %d\n", MAX(a + 2, b - 1));
return 0;
}