On the creative placement of #define
Monday, December 5th, 2011 18:16I just invented a new (to me) abuse of the C preprocessor. From a Stack Overflow answer I just wrote:
My understanding is that you are defining a constant, using it later to size one or more arrays, and also want that constant to be a symbol, preferably without a messy namespace. (If it were a matter of exporting the size of a single array, I would instead suggest sizeof(array) / sizeof(*array)
as missingno did.)
static const int ASIZE = 10; #define ASIZE 10 int array[ASIZE];
Here, there is a variable with the desired value which will be in the object file, but the preprocessor macro shadows it with the value itself, so the array definition also succeeds.
However, you may find the need to duplicate the value expression ugly. Wouldn't it be nice if we could define the variable in terms of the macro?
static const int ASIZE = #define ASIZE 10 ASIZE; int array[ASIZE];
I'm not sure whether this is actually a better idea maintainability-wise than the above, but it works (and I couldn't get gcc to be offended by it) and it contains no duplication other than of the identifier. And it's amusing.
Previous C adventures: A dreadful thing