More on Getting the Number of Array Elements

In a previous post, I discussed a safer way to get the number of elements in a C++ array. I mentioned that the countof() macro doesn’t work with local types (i.e. types defined inside a function definition).

I just realized that the macro also fails to work with anonymous types under certain circumstances. To be exact, If you call countof() on two arrays that have different anonymous types AND same size, then the second call will fail to compile.




    int x;

} g_a[100];



    int x;

} g_b[100];

    int g_size;


    g_size = countof( g_a ); // First call - OK

    g_size = countof( g_b ); // Second call - compiler ERROR!

The reason is that in this case, the second instantiation of the template helper function _ArraySizeHelper clashes with the first instantiation.

Note that if you change the size of g_b to something other than 100, it compiles fine.

So the caveat should be “countof() does not work with local types, and under certain circumstances does not work with anonymous types.”

I cannot believe it’s so difficult to get such a simple job (getting the number of array elements) done in C++.

What a broken language it is.