1

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.

strawbot
  • 11
  • 2
  • 2
    You could implement one of the techniques from the answer to http://stackoverflow.com/questions/3385515/static-assert-in-c or http://stackoverflow.com/questions/174356/ways-to-assert-expressions-at-build-time-in-c. Also, you should *always* put the macro arguments in paranthesis, like `(BQDATA)+(SIZE)+1`, otherwise you'll get problems with operator precedence. – Niklas B. Feb 20 '12 at 23:08

1 Answers1

1

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.

jørgensen
  • 10,149
  • 2
  • 20
  • 27