等同于其他编译器中的 MSVC 的 _countof? [英] Equivalents to MSVC's _countof in other compilers?

查看:13
本文介绍了等同于其他编译器中的 MSVC 的 _countof?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何与 等效的内置函数_countof 由其他编译器提供,特别是 GCC 和 Clang?有没有非宏形式?

Are there any builtin equivalents to _countof provided by other compilers, in particular GCC and Clang? Are there any non-macro forms?

推荐答案

我不知道有一个 GCC,但是 Linux 使用 GCC 的 __builtin_types_compatible_p 内置 使他们的 ARRAY_SIZE() 宏更安全(如果应用于指针会导致构建中断):

I'm not aware of one for GCC, but Linux uses GCC's __builtin_types_compatible_p builtin to make their ARRAY_SIZE() macro safer (it'll cause a build break if applied to a pointer):

/* &a[0] degrades to a pointer: a different type from an array */
#define __must_be_array(a) 
 BUILD_BUG_ON_ZERO(__builtin_types_compatible_p(typeof(a), typeof(&a[0])))

#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))

注意:我认为 BUILD_BUG_ON_ZERO() 宏的名称具有误导性(如果表达式 not 为零并返回 0 否则):

Note: I think the BUILD_BUG_ON_ZERO() macro has a misleading name (it causes a build failure if the expression is not zero and returns 0 otherwise):

/* Force a compilation error if condition is true, but also produce a
   result (of value 0 and type size_t), so the expression can be used
   e.g. in a structure initializer (or where-ever else comma expressions
   aren't permitted). */
#define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))

我认为这个宏的命名来自于两部分:BUILD_BUG_ON 是宏在表达式为真时所做的,ZERO 是值由宏返回"(如果没有构建中断).

I think the naming for this macro comes from looking at it in two parts: BUILD_BUG_ON is what the macro does when the expression is true, and ZERO is the value 'returned' by the macro (if there's not a build break).

这篇关于等同于其他编译器中的 MSVC 的 _countof?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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