Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematical operations during compiler preprocessing

I often have the situation where I need several constants generated at compile time for the use of bit shift and masking operations.

e.g.

#define blockbits 8
#define blocksize 256   // could be generated from 2^blockbits
#define blocksize 0xFF  // could be generated from blocksize - 1

I would like all these to be generated from blockbits, however there is no power operation that can be used in the preprocessor that I am aware of.

Does anyone know a simple way of generating this sort of thing at compile time?

like image 401
camelccc Avatar asked Nov 09 '12 23:11

camelccc


1 Answers

You can define them as mathematical expressions:

#define blockbits 8
#define blocksize (1 << blockbits) 
#define blockXXXX (blocksize - 1) // changed from blocksize to blockXXXX, since blocksize is already taken

The parentheses are to make sure there are no operator precedence issues when you use them in other expressions.

You also might want to change the names to all uppercase like BLOCKBITS, BLOCKSIZE, etc, which is a C++ naming convention to distinguish macros from normal names.

like image 130
Seth Carnegie Avatar answered Nov 02 '22 11:11

Seth Carnegie