Re: Counting array initializers
Rich Pasco wrote:
[..]
The problem is pretty much as I state. Eevery year or so I recompile
a program with a different list of names, and need to do a sanity
check on the number of names used.
I can omit the sanity check and use the macro as I defined it.
You need to quit trying to use the preprocessor for something it was
not designed to be used for. In most cases you just don't need the
preprocessor except to define some macros, perform conditional
compilation based on those macros or predefined macros from the
implementation and include some headers.
What you seem to need to do you can do with templates. The
simplest way is
// here are your check helpers
template<bool> struct arraysize;
template<> struct arraysize<true> { typedef int OK; };
#define SPLICE2(a, b) a ## b
#define SPLICE(a, b) SPLICE2(a, b)
#define CHECK_ARRAY(a) \
arraysize<sizeof(a)/sizeof(*a) <= maximum_size>::OK \
SPLICE(OK, __LINE__)()
// here is your code
const int maximum_size = 5;
char const* blah[] = { "abc", "def", "ghi" };
char const* blahblah[] = { "a", "b", "c", "d", "e", "f" };
CHECK_ARRAY(blah); // this should compile fine
CHECK_ARRAY(blahblah); // this should fail
int main()
{
}
You can massage it into giving a decent error message by changing
the actual cause of the failure to compile, by changing the names
of the involved macros/types/functions, etc.
Now, of course the failure is not on the same line as the array
that's too long. But then you can simply fall back onto
char const* badarray[maximum_size] = { ...
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask