在其他编译器中等同于MSVC的_countof?

是否有其他编译器提供的_countof内置等价物,尤其是GCC和Clang? 有没有非宏观forms?

使用C ++ 11,非宏forms是:

 char arrname[5]; size_t count = std::extent< decltype( arrname ) >::value; 

并且可以在type_traits标头中找到extent

或者,如果您希望它看起来更好一点,请将其包装在:

 template < typename T, size_t N > size_t countof( T ( & arr )[ N ] ) { return std::extent< T[ N ] >::value; } 

然后它变成:

 char arrname[5]; size_t count = countof( arrname ); char arrtwo[5][6]; size_t count_fst_dim = countof( arrtwo ); // 5 size_t count_snd_dim = countof( arrtwo[0] ); // 6 

编辑:我刚注意到“C”标志而不是“C ++”。 所以,如果你来这里是C,请好好忽略这篇文章。 谢谢。

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

 /* &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()宏有一个误导性的名称(如果表达式为零则导致构建失败,否则返回0 ):

 /* 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 eg 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是表达式为true时宏所执行的操作,而ZERO是宏返回的值(如果没有构建中断)。

这个?

#define _countof(a) (sizeof(a)/sizeof(*(a)))

更新:C ++ 17支持std::size() (在头文件定义)

您可以使用boost::size()代替:

 #include  int my_array[10]; boost::size(my_array);