Ask Learn
Preview
Please sign in to use this experience.
Sign inThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
_countof
MacroComputes the number of elements in a statically allocated array.
#define _countof(array) (sizeof(array) / sizeof(array[0]))
array
The name of an array.
The number of elements in the array, expressed as a size_t
.
_countof
is implemented as a function-like preprocessor macro. The C++ version has extra template machinery to detect at compile time if a pointer is passed instead of a statically declared array.
Ensure that array
is actually an array, not a pointer. In C, _countof
produces erroneous results if array
is a pointer. In C++, _countof
fails to compile if array
is a pointer. An array passed as a parameter to a function decays to a pointer, which means that within the function, you can't use _countof
to determine the extent of the array.
Macro | Required header |
---|---|
_countof |
<stdlib.h> |
// crt_countof.cpp
#define _UNICODE
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
int main( void )
{
_TCHAR arr[20], *p;
printf( "sizeof(arr) = %zu bytes\n", sizeof(arr) );
printf( "_countof(arr) = %zu elements\n", _countof(arr) );
// In C++, the following line would generate a compile-time error:
// printf( "%zu\n", _countof(p) ); // error C2784 (because p is a pointer)
_tcscpy_s( arr, _countof(arr), _T("a string") );
// unlike sizeof, _countof works here for both narrow- and wide-character strings
}
sizeof(arr) = 40 bytes
_countof(arr) = 20 elements
Please sign in to use this experience.
Sign in