const and #define Macros

Constants with const, and text-replacing macros with #define, including why macro arguments need brackets.

C · beginner · 6 min · 9 steps · free

What you'll learn

const_macros.c

#include <stdio.h>

#define SQUARE(x) ((x) * (x))
#define MAX_USERS 3

int main(void) {
    const double PI = 3.14159;            /* the compiler refuses any change to PI */
    int users[MAX_USERS] = {0};
    int s = SQUARE(4);
    int tricky = SQUARE(1 + 2);           /* thanks to the brackets: 9, not 5 */
    double area = PI * SQUARE(2);
    users[MAX_USERS - 1] = s;
    printf("%d %d %.2f %d\n", s, tricky, area, users[2]);
    return 0;
}

Step by step

  1. const: the compiler refuses any later assignment to PI.
  2. users is created on the stack with the value [0, 0, 0].
  3. SQUARE(4) is replaced by ((4) * (4)) before compiling: 16.
  4. SQUARE(1 + 2) becomes ((1 + 2) * (1 + 2)) = 9.
  5. area is created on the stack with the value 12.5664.
  6. users changes from [0, 0, 0] to [0, 0, 16].
  7. It prints 16 9 12.57 16.
  8. The method returns 0.
  9. 16 9 12.57 16.

Common mistakes

Best practices

Key takeaways

Check yourself

Does #define respect types?

Answer: No: it is text replacement. The compiler never sees the macro.

const int n = 3; n = 4;

Answer: Compile error. const forbids it.

·

More in Structs and Types