The ## operator in C

后端 未结 7 2180
花落未央
花落未央 2020-12-06 17:02

What does ## do in C?

Example:

typedef struct
{
    unsigned int bit0:1;
    unsigned int bit1:1;
    unsigned int bit2:1;
    unsigned          


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-06 17:19

    That's part of the macro definition.

    It allows you to concatenate strings inside the macro.

    In your case, you can use bt from 7 to 0 like this:

    REGISTER_BIT(myreg, 0)
    

    and it will be expanded as:

    ((volatile _io_reg*)&myreg)->bit0

    Without this, you'd have to define the bit part of the macro as one of the macro's arguments:

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

    where the usage would be:

    REGISTER_BIT(myreg, bit0)
    

    which is more cumbersome.

    This also allows you to build new names.

    Assume you have these macros:

    #define AAA_POS 1
    #define AAA_MASK (1 << AAA_POS)
    #define BBB_POS 2
    #define BBB_MASK (1 << BBB_POS)
    

    and you want a macro that extracts AAA from a bit vector. You can write it like this:

    #define EXTRACT(bv, field) ((bv & field##_MASK) >> field##_POS)
    

    and then you use it like this:

    EXTRACT(my_bitvector, AAA)
    

提交回复
热议问题