C 的通用数组长度宏? [英] Common array length macro for C?

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

问题描述

我见过几个数组长度的宏:

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

来自这个问题:

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

和 Visual Studio 的 _countof:

And Visual Studio's _countof:

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

我想知道的是:

  1. 使用 array[0]*array 的那些有什么区别?
  2. 为什么应该首选?
  3. 它们在 C++ 中是否有所不同?
  1. What's the difference between those using array[0] and *array?
  2. Why should either be preferred?
  3. Do they differ in C++?

推荐答案

这是一个更好的 C 版本(来自 Google 的 Chromium 项目):

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])))))

它在array[0]*array版本的基础上改进,使用了0[array],相当于array[0] 在普通数组上,但如果 array 恰好是重载 operator[]() 的 C++ 类型,将无法编译.

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[]().

对于许多(但不是全部)指针作为 array<传递的情况,除法会导致除以零操作(应该在编译时捕获,因为它是编译时常量表达式)/code> 参数.

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.

C 中有没有标准函数可以返回数组的长度? 了解更多详情.

C++ 代码有更好的选择.有关详细信息,请参阅不使用宏编译时 sizeof_array.

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

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

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