What will be the output of program
#include
int fun(char *a){
printf(\"%d\\n\",sizeof(a));
return 1;
}
int main(){
char a[20];
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.
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
operators2 [...] 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.
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).
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