C Preprocessor for Array Values

Macros don't need to conform to C syntax.

# c

2023-10-21


A good way to think of, #define, and other pre-processor directives, is basically as a “find and replace” operation that happens before the code is compiled. You don’t follow C syntax as in the rest of the program body.

#define VALUE 42
static const unsigned int array[1] = { VALUE };

It’s easy to see that the value of VALUE can be used in the creation of an array. And #define can be used to create function-like macros too:

#define PLUS_ONE(n) n+1
static const unsigned int array[1] = { PLUS_ONE(41) };

The previous two code snippets would ultimately result in the same executable. Just to drive home the idea that this is basically a “find and replace” happening, the following two snippets are also equal (in terms of the end result).

#define A 1
#define B 2
static const unsigned int array[2] = { A, B };
#define AB 1, 2
static const unsigned int array[2] = { AB };

Invoke the C Preprocessor using, cpp <filename>, to see the substitutions it made. Both snippets result in the same thing.

# 1 "macro_demo.c"
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 369 "<built-in>" 3
# 1 "<command line>" 1
# 1 "<built-in>" 2
# 1 "macro_demo.c" 2


static const unsigned int array[2] = { 1, 2 };

int main(void) {
  return 0;
}