The _countof macro

VC++ 2005 provides an _countof macro that returns the number of elements in a statically-allocated array. You cannot use it with a pointer type. It’s different from sizeof in the sense that sizeof returns the size in bytes and also works on pointers, though for pointers, it actually returns the size of the pointer (4 bytes on a 32-bit system).

The following code snippet shows them both in action :-

char s1[20] = "hello";
wchar_t s2[20] = L"hello";
const char* s3 = "hello";
const wchar_t* s4 = L"hello";
char* s5 = new char[128];

cout << sizeof s1 << endl;//20
cout << sizeof s2 << endl;//40
cout << sizeof s3 << endl;//4
cout << sizeof s4 << endl;//4
cout << sizeof s5 << endl;//4

cout << _countof(s1) << endl;//20
cout << _countof(s2) << endl;//20
//cout << _countof(s3) << endl; <-- won't compile
//cout << _countof(s4) << endl; <-- won't compile
//cout << _countof(s5) << endl; <-- won't compile

delete[] s5;
Advertisements
Posted in C++

5 thoughts on “The _countof macro

  1. For a long time (VC++ 6), I have been using such a macro, that I have defined like this:

    #define CountOf(array) (sizeof(array)/sizeof(array[0]))

    It is so useful, especially when using arrays of initialized data.

    struct tagS {INT a; INT b;} data[] =
    {
    {0, 1},
    {2, 3},
    };

    for(INT i=0; i<CountOf(data); i++)
    {
    cout << data[i].a;
    cout << data[i].b;
    }

    When adding new items in the array, it’s so easy. No need to take care about how many items you add and no need to update accordingly the for loop counter. How is defined this macro in VC++ 2005 ?

    1. How do you get around the “incomplete” type warning from Visual Studio?

      The warning is because this requires multiple passes by the compiler. Instead of a dynamically sized array, I rely on a length constant and compile-time warnings to indicate a mismatch in the number of elements.

  2. I use the same definition as Stlan, but I have always called mine _countof.

    The VC2005 definition is in stdlib.h. If __cplusplus is not defined, the definition is the same as we’ve always used. If __cplusplus *is* defined, it wraps a bizarre object which is an array of template function pointers, where the array size is deduced through template parameter inference.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s