What does the sizeof (function (argument)) function return?

What will be the output of the 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; } 
+7
source share
4 answers

With the exception of variable-length arrays, sizeof does not evaluate its operand. Thus, it will simply give the size fun(a) , i.e. sizeof(int) (without calling a function).

C11 (n1570) ยง6.5.3.4 sizeof and _Alignof

2 [...] If the operand type is an array of variable length, then the operand is evaluated; otherwise, the operand is not evaluated, and the result is an integer constant.

+16
source

It returns the size of the return type from this function ( 4 in my implementation since int used for me), which you will find if you run it as it is, and then change the return type to char (at that moment it will give you 1 ).

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

The sizeof operator gives the size (in bytes) of its operand, which can be an expression or a type name enclosed in brackets. Size is determined by the type of operand. The result is an integer. If the operand type is an array type of variable length, then the operand is evaluated; , then the operand is not evaluated , and the result is an integer constant.

Keep in mind this bold bit, this means that the function itself is not called (therefore, printf is not executed inside it). In other words, the output is just the size of your int type (followed by, of course, a new line).

+4
source

The function returns int , so it is sizeof(int) , which on 32-bit systems is usually 4 bytes. Although it may be 2 or 8, depending on implementation.

+3
source

the sizeof keyword, followed by an ellipsis, returns the number of elements in the parameter package.

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

+1
source

All Articles