Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count lines between two code locations in C preprocessor

I want to use the C preprocessor to count the amount of lines between two code locations. The basic idea is something like this:

#define START __LINE__
static char* string_list[] = {
    "some string",
    "another string",
    ...
    "last string"
};
#define END __LINE__
#if END - START > 42
    #error Too many entries
#endif

Of course this doesn't work because in this case START and END are merely redefinitions of the __LINE__ macro.
I was playing around a bit with the # and ## operators, but I could not get the preprocessor to evaluate START and END while the preprocessor is running.

My question is: is this possible at all?

Checking the size of the array during runtime is not an option.
Thanks for any hints or ideas in advance!

like image 226
Chris Avatar asked Jul 03 '14 10:07

Chris


1 Answers

You shouldn't use those macros for that purpose: the code will become completely unmaintainable if you introduce an extra line somewhere. And what if there are too few lines?

Instead of macros, use a static assert:

static_assert(sizeof(string_list) / sizeof(*string_list) == SOME_CONSTANT,
               "Wrong number of entries in string list.");

If you aren't using C11 which has support for static_assert, you can write such an assert yourself, for example like this:

#define COMPILE_TIME_ASSERT(expr) {typedef uint8_t COMP_TIME_ASSERT[(expr) ? 1 : 0];}
like image 178
Lundin Avatar answered Sep 30 '22 10:09

Lundin