strawbot
strawbot

Reputation: 11

parameter check in C macro

I would like to define a macro which will also check limits on its arguments. For example:

typedef unsigned char Byte;
#define BQDATA 3
#define MAX_BQ_SIZE (255-BQDATA)

#define BQ(SIZE,NAME)   \
    #if SIZE > MAX_BQ_SIZE \
         #error BQ NAME exceeds maximum size \
    #endif \
    Byte NAME[BQDATA+SIZE+1] = {BQDATA,BQDATA,BQDATA+SIZE}

So that if it encounters:

BQ(300,bigq);

It would flag the error.

Upvotes: 1

Views: 2318

Answers (1)

jørgensen
jørgensen

Reputation: 10551

If size and max_bq_size are compile-time constants you can use #define BQ(size, name)BUILD_BUG_ON(size > max_bq_size);. You don't get a custom message, but at least an error.

Upvotes: 1

Related Questions