C Macro Syntax

C Macro Syntax

This document summarizes C language macro syntax.

1. Stringification Operator (#)

1
2
3
4
5
6
7
8
#include <stdio.h>
#define PRINT(s)    printf(#s)

int main()
{
    PRINT(THIS IS TEST CODE);                          
    return 0;
}
[Code 1] # Macro Example
THIS IS TEST CODE
[Shell 1] # Macro Example Output

The stringification operator (#) converts macro parameters to strings. It has the same effect as adding " ". [Code 1] shows an example where the THIS IS TEST CODE macro parameter is passed as a string to the printf() function.

2. Token Pasting Operator (##)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include <stdio.h>

#define INT_i(n)        int i##n = n;
#define PRINT(n)        printf("i%d = %d\n", n, i##n)

int main()
{
    INT_i(0);
    PRINT(0);

    return 0;
}
[Code 2] ## Macro Example
i0 = 0
[Shell 2] ## Macro Example Output

The token pasting operator (##) combines separate tokens into one. In [Code 2], the INT_i() macro function is replaced with int i0 = 0, and the PRINT() macro function is replaced with printf("i%d = %d\n", 0, i0).

3. Variadic Macro

1
#define debug(format, ...) fprintf (stderr, format, __VA_ARGS__)
[Code 3] 1999 Standard Variadic Macro
1
#define debug(format, args...) fprintf (stderr, format, args)
[Code 4] GCC Variadic Macro

The 1999 C standard uses ... and __VA_ARGS__ to represent variadic arguments. [Code 3] shows the usage of variadic macros in the 1999 C standard syntax. GCC uses [name]... and [name] to represent variadic arguments. [Code 4] shows the usage of GCC variadic macros.

4. References