Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The ## operator in C

Tags:

c

What does ## do in C?

Example:

typedef struct
{
    unsigned int bit0:1;
    unsigned int bit1:1;
    unsigned int bit2:1;
    unsigned int bit3:1;
    unsigned int bit4:1;
    unsigned int bit5:1;
    unsigned int bit6:1;
    unsigned int bit7:1;
} _io_reg;

#define REGISTER_BIT(rg,bt) ((volatile _io_reg*)&rg)->bit##bt

(I know what it all does besides the ## part.)

like image 305
Michael Avatar asked Feb 29 '12 06:02

Michael


3 Answers

It is string concatenation, as part of the preprocessor macro.

(In this context, "string" refers to a preprocessor token of course, or a "string of source code", and not a C-string.)

like image 200
Kerrek SB Avatar answered Nov 06 '22 02:11

Kerrek SB


It's called the pasting operator; it concatenates the text in bt with the text bit. So for example, if your macro invocation was

REGISTER_BIT(x, 4)

It would expand to

((volatile _io_reg*)&x)->bit4

Without it, you couldn't put a macro argument directly beside text in the macro body, because then the text would touch the argument name and become part of the same token, and it'd become a different name.

like image 21
Seth Carnegie Avatar answered Nov 06 '22 01:11

Seth Carnegie


The operator ## concatenates two arguments leaving no blank spaces between them:

#define glue(a,b) a ## b
glue(c,out) << "test";
like image 30
Aman Aggarwal Avatar answered Nov 06 '22 01:11

Aman Aggarwal