Why does decay to pointer for array argument appear not to apply to sizeof()?

后端 未结 2 1696
旧时难觅i
旧时难觅i 2020-12-20 16:31

I read a question earlier that was closed due to being an exact duplicate of this

When a function has a specific-size array parameter, why is it replaced with a poin

相关标签:
2条回答
  • 2020-12-20 17:04

    sizeof is an operator, not a function. It's a specific one at that, too. The parentheses aren't even necessary if it's an expression:

    int a;
    sizeof (int); //needed because `int` is a type
    sizeof a; //optional because `a` is an expression
    sizeof (a); //^ also works 
    

    As you can see, it's on this chart of precedence as well. It's also one of the non-overloadable operators.

    0 讨论(0)
  • 2020-12-20 17:08

    Because the standard says so (emphasis mine):

    (C99, 6.3.2.1p3) "Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue."

    Note that for C++, the standard explicitly says the size is the size of the array:

    (C++11, 5.3.3p2 sizeof) "[...] When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element."

    0 讨论(0)
提交回复
热议问题