PreProcessing #define

224 views Asked by At

I am unable to understand how the preprocessor works and what does the ## stands for in this particular example

#include <stdio.h>

#define TEMP_KEY(type,Key) (TEMP_##type | Key)

enum TEMPKey_Type
{
    TEMP_UNKNOWN = 0,
    TEMP_SPECIAL ,
    TEMP_UNICODE
};

enum Actual_Key
{
    TEMP_RIGHT = TEMP_KEY(UNKNOWN,0x1),
    TEMP_LEFT = TEMP_KEY(SPECIAL,0x1),
    TEMP_UP = TEMP_KEY(UNICODE,0x1)
};

int main()
{
    printf("\n Value of TEMP_RIGHT : %d ",TEMP_RIGHT);
    printf("\n Value of TEMP_LEFT : %d ",TEMP_LEFT);
    printf("\n Value of TEMP_UP : %d ",TEMP_UP);

    return 0;
}

How does this #define TEMP_KEY(type,Key) (TEMP_##type | Key) work or how and what exactly is TEMP_##type replaced by during preprocessing?

2

There are 2 answers

1
qbert220 On

The "##" means concatenate. Therefore TEMP_RIGHT = TEMP_KEY(UNKNOWN,0x1) becomes TEMP_RIGHT = TEMP_UNKNOWN | 0x1, ("TEMP_" and "UNKNOWN" are joined together)

2
artyom.stv On

## is the concatenation operator in #define directives.

For example, TEMP_##type for TEMP_KEY(UNICODE,0x1) call generates next code:

(TEMP_UNICODE | 0x1)