Can “sizeof(arr[0])” lead to undefined behavior?

后端 未结 5 1422
长发绾君心
长发绾君心 2020-12-31 05:31

There is a well known pattern of figuring out array length:

int arr[10]; 
size_t len = sizeof(arr) / sizeof(arr[0]); 
assert(len == 10); 

T

5条回答
  •  悲哀的现实
    2020-12-31 05:57

    The expression ptr[0] will not be evaluated in sizeof(ptr[0]). Size will be determined by just using the type of ptr[0] at compile time.

    C11: 6.5.3.4:

    The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is aninteger constant.

    That means, there is no undefined behavior.

提交回复
热议问题