_countof Macro
Compute the number of elements in a statically-allocated array.
_countof( array );
// crt_countof.cpp
#define _UNICODE
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
int main( void )
{
_TCHAR arr[20], *p;
printf( "sizeof(arr) = %d bytes\n", sizeof(arr) );
printf( "_countof(arr) = %d elements\n", _countof(arr) );
// In C++, the following line would generate a compile-time error:
// printf( "%d\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
Re: What is the C++ version doing
There is a good explanation here:
http://social.msdn.microsoft.com/Forums/en/vclanguage/thread/252b4be3-8adf-49e4-a240-93ccb91849f2
$0$0
$0
- 3/9/2012
- Baloo0402
What is the C++ version doing?
Can anyone help explain in detail how the C++ version works?
template <typename _CountofType, size_t _SizeOfArray>
char (*__countof_helper(UNALIGNED _CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray];
#define _countof(_Array) (sizeof(*__countof_helper(_Array)) + 0)
Some things I don't get:
- What is the type of __countof_helper?
- What is the * in sizeof(*__countof_helper(_Array)) doing? Knowing the type of __countof_helper will probably help here.
- What is the + 0 doing?
- 8/27/2010
- c45207