本文介绍了宏定义ARRAY_SIZE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Google v8项目中阅读globals.h时,我遇到了以下宏定义。

I encountered the following macro definition when reading the globals.h in the Google v8 project.

// The expression ARRAY_SIZE(a) is a compile-time constant of type
// size_t which represents the number of elements of the given
// array. You should only use ARRAY_SIZE on statically allocated
// arrays.

#define ARRAY_SIZE(a)                               \
  ((sizeof(a) / sizeof(*(a))) /                     \
  static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))

我的问题是后一部分: static_cast< size_t>(!(sizeof(a)%sizeof(*(a)))))。在我的心中有一件事是:因为后面的部分将总是评估 1 ,类型 size_t ,所以整个表达式将被提升为 size_t 。如果这个假设是正确的,那么还有另一个问题:由于 sizeof 运算符的返回类型是size_t,为什么这样的提升是必要的?以这种方式定义宏有什么好处?

My question is the latter part: static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))). One thing in my mind is the following: Since the latter part will always evaluates to 1, which is of type size_t, so the whole expression will be promoted to size_t. If this assumption is correct, then there comes another question: since the return type of sizeof operator is size_t, why such promotion is necessary? What's the benefit of defining a macro in this way?

非常感谢您阅读。

推荐答案

理想情况下,后面的部分将评估为 bool (即 true / false )并使用 static_cast<> ,将其转换为 size_t

Ideally the later part will evaluate to bool (i.e. true/false) and using static_cast<>, it's converted to size_t.

我不知道这是否是理想的定义方式一个宏。但是,我发现的一个灵感是在评论: //你应该只使用ARRAY_SIZE静态分配的数组。

I don't know if this is ideal way to define a macro. However, one inspiration I find is in the comments: //You should only use ARRAY_SIZE on statically allocated arrays.

假设,如果有人传递指针,则 struct (如果大于指针大小)数据类型将失败。

Suppose, if someone passes a pointer then it would fail for the struct (if it's greater than pointer size) data types.

struct S { int i,j,k,l };
S *p = new S[10];
ARRAY_SIZE(p); // compile time failure !

[注意:此技术可能不会显示 int * code>, char * 如所述。]

[Note: This technique may not show any error for int*, char* as said.]

这篇关于宏定义ARRAY_SIZE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:55