常见的数组长度宏对C? [英] Common array length macro for C?

查看:351
本文介绍了常见的数组长度宏对C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了数组长度几个宏左右浮动:

从<一个href=\"http://stackoverflow.com/questions/4307929/is-there-any-shortcut-for-array-size-length-in-c\">this问题:


  • 的#define长度(阵列)(的sizeof(阵列)/ sizeof的(*(阵列)))

  • 的#define ARRAY_LENGTH(阵列)(的sizeof((阵列))/ sizeof的((阵列)[0]))

  • 的#define SIZE(数组类型)(的sizeof(阵列)/(的sizeof(型))

和Visual Studio的<一个href=\"http://msdn.microsoft.com/en-us/library/ms175773%28v=VS.100%29.aspx\"><$c$c>_countof:

 的#define _countof(_Array)(的sizeof(_Array)/ sizeof的(_Array [0]))

我想知道的是:


  1. 什么是使用这些之间的差异数组[0] *阵列

  2. 为什么不是应该是preferred?

  3. 请他们用C ++不同?


解决方案

下面是一个更好的C版(可从谷歌的Chromium项目):

 的#define COUNT_OF(X)((的sizeof(X)/ sizeof的(0 [X]))/((为size_t)(!(的sizeof(X)%的sizeof(0 X])))))

这改善了数组[0] *阵列版本通过使用 0 [阵列] ,相当于数组[0] 在普通阵列,但将无法编译,如果阵列恰好是一个C ++类型重载运算符[]()

该部门的除数零操作(应该在编译时被捕获,因为它是一个编译时间常数前pression)许多(但不是全部),其中一个指针作为传递情况阵列参数。

请参阅Is有一个标准的函数C,它会返回一个数组的长度? ,获取更多详情。

有对C ++ code是更好的选择。见<一href=\"http://stackoverflow.com/questions/1500363/compile-time-sizeofarray-without-using-a-macro/1500917#1500917\">Compile时间sizeof_array不使用宏获得详细信息。

I've seen several macros for array length floating around:

From this question:

  • #define length(array) (sizeof(array)/sizeof(*(array)))
  • #define ARRAY_LENGTH(array) (sizeof((array))/sizeof((array)[0]))
  • #define SIZE(array, type) (sizeof(array) / (sizeof(type))

And Visual Studio's _countof:

#define _countof(_Array) (sizeof(_Array) / sizeof(_Array[0]))

What I'd like to know is:

  1. What's the difference between those using array[0] and *array?
  2. Why should either be preferred?
  3. Do they differ in C++?

解决方案

Here's a better C version (from Google's Chromium project):

#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))

It improves on the array[0] or *array version by using 0[array], which is equivalent to array[0] on plain arrays, but will fail to compile if array happens to be a C++ type that overloads operator[]().

The division causes a divide-by-zero operation (that should be caught at compile time since it's a compile-time constant expression) for many (but not all) situations where a pointer is passed as the array parameter.

See Is there a standard function in C that would return the length of an array? for more details.

There's a better option for C++ code. See Compile time sizeof_array without using a macro for details.

这篇关于常见的数组长度宏对C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆