cc-preprocessorx-macros

Understanding the text replacement in x macro


The code below explain how the x macros works in a simple way in c programming langauge

#include <stdio.h> 

// Defines four variables. 
#define VARIABLES \ 
    X(value1, 1)  \ 
    X(value2, 2)  \ 
    X(value3, 3)  \ 
    X(value4, 4) 

// driver program. 
int main(void) 
{ 
    // Declaration of every variable 
    // is done through macro. 
    #define X(value, a) char value[10]; 
        VARIABLES 
    #undef X 

    // String values are accepted 
    // for all variables. 
    #define X(value, a) scanf("\n%s", value); 
        VARIABLES 
    #undef X 

    // Values are printed. 
    #define X(value, a) printf("%d) %s\n", a, value); 
        VARIABLES 
    #undef X 
    return 0; 
} 

Form the definion of the macros in c. it is just a text replacement tool. so the compiler will recreate the code in the following way below:

#include <stdio.h> 

int main(void) 
{ 
    char value1[10]; 
    char value2[10]; 
    char value3[10]; 
    char value4[10]; 

    scanf("\n%s", value1); 
    scanf("\n%s", value2); 
    scanf("\n%s", value3); 
    scanf("\n%s", value4); 

    printf("%d) %s\n", 1, value1); 
    printf("%d) %s\n", 2, value2); 
    printf("%d) %s\n", 3, value3); 
    printf("%d) %s\n", 4, value4); 
    return 0; 
} 

The preprocessor will replace

VARIABLES ------> X(value1, 1) X(value2, 2) X(value3, 3) X(value4, 4)

And it will replace X(value1, 1) with char value[10]; in the following way

X(value1, 1)      char value[10];
  -----                -----
    v                    ^
    |                    |
    +--------------------+

//how the code become like this ?

 char value1[10];

//why not like this?

char value[10]1;

//or like this?

char value[10];1

//why the macro consider value as the text and place 1 immediately after it?

And what about the second argument 1, is it going to be replaced with something?

X(value1, 1) 
         ---             
          ^                    
          |                    
//where is this parameter replaced with    

Solution

  • In #define X(value, a), the value and a are macro parameters. If you pass X(value1, 1) then those will become the values of these macro parameters, kind of like when you pass parameters to a function.

    In the case of #define X(value, a) char value[10];, the parameter a isn't used in the macro so it is just ignored.

    This is common when using X macros, you might have several values but only some that make sense to use in a specific case. You will still have to pass all parameters, but using them in each macro is optional.

    It works just like plain old functions. This function is perfectly valid:

    void foo (int a, int b)
    {
      printf("%d", a);
    }
    

    Where did b go? Nowhere, the function simply did not use it.