carraysgccmacrosclang

Equivalents to MSVC's _countof in other compilers?


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


Solution

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

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

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