_countof宏应用

在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]))
#else
extern "C++"
{
template <typename _CountofType, size_t _SizeOfArray>
char (*__countof_helper(UNALIGNED _CountofType (&_Array)[_SizeOfArray]))[_SizeOfArray];
#define _countof(_Array) sizeof(*__countof_helper(_Array))
}
#endif
#endif 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值