Why does the following code give:
#include<stdio.h>
int voo()
{
printf ("Some Code");
return 0;
}
int main() {
printf ("%zu", sizeof voo);
return 0;
}
The following output:
1
Why does the following code give:
#include<stdio.h>
int voo()
{
printf ("Some Code");
return 0;
}
int main() {
printf ("%zu", sizeof voo);
return 0;
}
The following output:
1
The C language does not define sizeof
for functions. The expression sizeof voo
violates a constraint, and requires a diagnostic from any conforming C compiler.
gcc implements pointer arithmetic on function pointers as an extension. To support this, gcc arbitrarily assumes that the size of a function is 1, so that adding, say, 42 to the address of a function will give you an address 42 bytes beyond the function's address.
They did the same thing for void, so sizeof (void)
yields 1, and pointer arithmetic on void*
is permitted.
Both features are best avoided if you want to write portable code. Use -ansi -pedantic
or -std=c99 -pedantic
to get warnings for this kind of thing.
The C99 Standard says:
6.3.2.1/4
Except when it is the operand of the sizeof operator 54) or the unary & operator, a function designator with type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to function returning type’’.
and in the 54) footnote, it says
Because this conversion does not occur, the operand of the sizeof operator remains a function designator and violates the constraint in 6.5.3.4.
The relevant passage out of 6.5.3.4 is
The sizeof operator shall not be applied to an expression that has function type or an incomplete type
From which we can conclude your program invoked Undefined Behaviour and no explanation can be given for the output.