What does sizeof (function(argument)) return?

后端 未结 4 682
滥情空心
滥情空心 2020-12-19 06:31

What will be the output of program

#include 

int fun(char *a){
    printf(\"%d\\n\",sizeof(a));
    return 1;
}

int main(){
    char a[20];
         


        
相关标签:
4条回答
  • 2020-12-19 07:17

    The function returns int, so it's sizeof(int), which, on 32 bit systems is typically 4 bytes. Though it could be 2 or 8, depending on implementation.

    0 讨论(0)
  • 2020-12-19 07:25

    Except with variable length arrays, sizeof does not evaluate its operand. So it will just yield the size of fun(a) type, i.e. sizeof(int) (without calling the function).

    C11 (n1570) §6.5.3.4 The sizeof and _Alignof operators

    2 [...] 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 an integer constant.

    0 讨论(0)
  • 2020-12-19 07:32

    It returns the size of the return type from that function (4 on my implementation since that's what an int takes up for me), which you would discover had you run it as is, then changed the return type to char (at which point it would give you 1).

    The relevant part of the C99 standard is 6.5.3.4.The sizeof operator:

    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 an integer constant.

    Keep in mind that bold bit, it means that the function itself is not called (hence the printf within it is not executed). In other words, the output is simply the size of your int type (followed by a newline, of course).

    0 讨论(0)
  • 2020-12-19 07:32

    keyword sizeof followed by ellipsis returns the number of elements in a parameter pack.

    The type of the result is the unsigned integral type size_t defined in the header file

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