ARRAYSIZE C ++宏:它是如何工作的? [英] ARRAYSIZE C++ macro: how does it work?
问题描述
好的,我不是完全新手,但我不能说我理解下面的宏。最令人困惑的部分是将价值除以size_t:什么是完成的?特别是,因为我看到一个否定运算符,据我所知,可能会导致一个零值。这不是意味着它可以导致一个除以0的错误? (顺便说一下,宏是正确的,并且工作得很漂亮。)
OK, I'm not entirely a newbie, but I cannot say I understand the following macro. The most confusing part is the division with value cast to size_t: what on earth does that accomplish? Especially, since I see a negation operator, which, as far as I know, might result in a zero value. Does not this mean that it can lead to a division-by-zero error? (By the way, the macro is correct and works beautifully.)
#define ARRAYSIZE(a) \
((sizeof(a) / sizeof(*(a))) / \
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
推荐答案
第一部分 sizeof(a)/ sizeof(*(a)))
是相当简单;它将整个数组的大小(假设你传递一个数组类型的对象,而不是一个指针)的大小除以第一个元素的大小。这给出了数组中元素的数量。
The first part (sizeof(a) / sizeof(*(a)))
is fairly straightforward; it's dividing the size of the entire array (assuming you pass the macro an object of array type, and not a pointer), by the size of the first element. This gives the number of elements in the array.
第二部分不是那么简单。我认为潜在的除零是故意的;如果由于某种原因,数组的大小不是其中一个元素的整数倍,它将导致编译时错误。换句话说,它是某种编译时的健全检查。
The second part is not so straightforward. I think the potential division-by-zero is intentional; it will lead to a compile-time error if, for whatever reason, the size of the array is not an integer multiple of one of its elements. In other words, it's some kind of compile-time sanity check.
但是,我看不出在什么情况下可能发生...正如人们建议的下面,它会捕获一些误用(如在指针上使用 ARRAYSIZE()
)。但它不会捕获所有的错误,
However, I can't see under what circumstances this could occur... As people have suggested in comments below, it will catch some misuse (like using ARRAYSIZE()
on a pointer). It won't catch all errors like this, though.
这篇关于ARRAYSIZE C ++宏:它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!