0

These 2 arrays are being modified a lot in the source code, that is why I want the preprocessor to count the number of members in the array. Is it also possible to have the gcc preprocessor check that array a ends in NULL and array b ends in 0?

static const char *a[] = { "string1", "string2", NULL };

static const int b[] = { 10, 20, 0 };
AstroCB
  • 12,337
  • 20
  • 57
  • 73
elaine
  • 119
  • 5
  • 1
    The preprocessor doesn't know anything about arrays... So I don't think it can check anything like than. You should clarify what you are trying to do. – hivert Jul 26 '13 at 17:16
  • 1
    No, you can't do this using the preprocessor, you have to pay attention. Or even better, require storing the length of the array explicitly. –  Jul 26 '13 at 17:20

1 Answers1

2

There are a few things the preprocessor can do for you, but not quite what you describe. You can determine the number of elements in the array using a macro:

#define COUNTOF(arr)  (sizeof(arr) / sizeof(*(arr)))

then somewhere in a function you can use assert() to test the values:

#include <assert.h>
...
... in some function
...

assert(a[COUNTOF(a) - 1] == NULL);
assert(b[COUNTOF(b) - 1] == 0);

or something to that effect.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
andy mango
  • 1,526
  • 1
  • 8
  • 13