我正在学习/阅读一些 openGL。我目前正在学习来自 http://www.arcsynthesis.org/gltut/ 的教程.该程序有一个用于数组长度的宏。我知道数组长度计算为 (sizeof( array )/(sizeof( array[0] )
。
但是代码有一些额外的东西所以最终的宏是:
#define ARRAY_COUNT( array ) (sizeof( array ) / (sizeof( array[0] ) * (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*))))
我无法理解为什么要将它乘以 bool
。
最佳答案
增加的是检查指针而不是数组的一些错误用法:
long long buf[42];
long long *p = buf;
ARRAY_COUNT(p); // this produces a compilation error : division by zero.
但它未能检测到一些不良用法:
char buf[42];
char *p = buf;
ARRAY_COUNT(p); // this gives unexpected result.
检查无法检测大小小于或等于指针的类型的错误使用。
C++ 的方法是:
template <typename T, std::size_t N>
constexpr std::size_t ArraySize(T (&)[N]) { return N; }
关于c++ - 从过剩教程中了解宏测量数组计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25349689/