How does “sizeof” work in this helper for determining array size?

前端 未结 3 2088
情话喂你
情话喂你 2020-12-18 11:45

I\'ve found this article that brings up the following template and a macro for getting array size:

template
char ( &Arr         


        
3条回答
  •  星月不相逢
    2020-12-18 12:25

    template
    char (&ArraySizeHelper(Type(&Array)[Size]))[Size];
    #define _countof(Array) sizeof(ArraySizeHelper(Array))
    

    sizeof is applied to a function declaration. I'd expect the result to be "size of function pointer". Why does it obtain "size of return value" instead?

    It's not sizeof ArraySizeHelper (which would be illegal - can't take sizeof a function), nor sizeof &ArraySizeHelper - not even implicitly as implicit conversion from function to pointer-to-function is explicitly disallowed by the Standard, for C++0x see 5.3.3). Rather, it's sizeof ArraySizeHelper(Array) which is equivalent to sizeof the value that the function call returns, i.e. sizeof char[Size] hence Size.

提交回复
热议问题