What does sizeof (function(argument)) return?

12,071

Solution 1

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.

Solution 2

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

Solution 3

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.

Solution 4

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

Share:
12,071
Bharat Kul Ratan
Author by

Bharat Kul Ratan

Graduated from Indian Instituted of Information Technology, Allahabad

Updated on June 04, 2022

Comments

  • Bharat Kul Ratan
    Bharat Kul Ratan almost 2 years

    What will be the output of program

    #include <stdio.h>
    
    int fun(char *a){
        printf("%d\n",sizeof(a));
        return 1;
    }
    
    int main(){
        char a[20];
        printf("%d\n",sizeof (fun(a)));
        return 0;
    }