宏定义ARRAY_SIZE [英] Macro definition ARRAY_SIZE

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

问题描述

我读了谷歌的V8项目globals.h时遇到下面的宏定义。

  //这位前pression ARRAY_SIZE(a)是类型的编译时间常数
//为size_t从而重新presents给定的元素数
//数组。您应该只使用ARRAY_SIZE的静态分配
//数组。#定义ARRAY_SIZE(一)\\
  ((sizeof的(A)/的sizeof(*(一)))/ \\
  的static_cast&所述;为size_t>(!(sizeof的(一)%的sizeof(*(一)))))

我的问题是后半部分:的static_cast<为size_t>)((的sizeof(A)%的sizeof(*(一)))!)。在我心中有一件事是:由于后期将始终计算为 1 ,这类型的为size_t ,因此整个前pression将晋升为为size_t 。如果这个假设是正确的,那么总会有另一个问题:因为的sizeof的的返回类型运算符是为size_t,为什么这样的推广是必要的吗?什么是这样定义宏的好处?

非常感谢您的阅读。


解决方案

  

后期将始终计算为1,这是size_t类型,


理想情况下,后期将计算为布尔(即真正 / ),并使用的static_cast<> ,它转换为为size_t


  

为什么这样推广是必要的吗?什么是定义的好处
  在这样的宏观?


我不知道这是否是定义一个宏理想的方式。然而,一个灵感,我觉得是在注释: //您应该只使用ARRAY_SIZE在静态分配的数组

假设,如果有人经过一个指针,然后它会失败的结构(如果它比指针大小更大)的数据类型。

 的struct {INT I,J,K,L};
S * p =新S [10];
ARRAY_SIZE(P); //编译时失败!

[注:此方法可能不会显示为int * 的char * 如说任何错误。]

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

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?

Thank you very much for reading.

解决方案

latter part will always evaluates to 1, which is of type size_t,

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

why such promotion is necessary? What's the benefit of defining a macro in this way?

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.

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 !

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

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

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