_countof宏应用

来源:互联网 发布:电影票比价软件 编辑:程序博客网 时间:2024/05/18 02:43

在MSDN上面查到一个宏_countof,很好用,作用是可以直接返回静态数组的元素个数。

MSDN上这么介绍这个宏的:

 

_countof宏:计算静态数组元素的个数。

用法:_countof(array);

 

所需头文件:<stdlib.h>

 

示例如下:

#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
}

 

在VS2005上面输出结果如下:

sizeof(arr) = 40 bytes_countof(arr) = 20 elements
如果屏蔽掉#define _UNICODE 这句,那么输出结果又是:
sizeof(arr) = 20 bytes_countof(arr) = 20 elements
其定义如下:
/* _countof helper */#if !defined(_countof)#if !defined(__cplusplus)#define _countof(_Array) (sizeof(_Array) / sizeof(_Array[0]))#elseextern "C++"{template <typename _CountofType, size_t _SizeOfArray>char (*__countof_helper(UNALIGNED _CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray];#define _countof(_Array) sizeof(*__countof_helper(_Array))}#endif#endif