Result of using sizeof for function

Why is the following code given:

#include<stdio.h> int voo() { printf ("Some Code"); return 0; } int main() { printf ("%zu", sizeof voo); return 0; } 

The following conclusion:

 1 
+5
source share
2 answers

C does not define sizeof for functions. The expression sizeof voo violates the constraint and requires diagnostics from any relevant C compiler.

gcc implements pointer arithmetic on function pointers as an extension. To support this, gcc arbitrarily assumes that the size of the function is 1, so adding, say 42 to the function address will give you the address 42 bytes after the function address.

They did the same for void, so sizeof (void) gives 1, and void* pointer arithmetic is allowed.

Both functions are best avoided if you want to write portable code. Use -ansi -pedantic or -std=c99 -pedantic to get warnings about this.

+9
source

The C99 standard says:

6.3.2.1/4

Unless the operand of the operator sizeof 54) is either unary or operator, the function designation with the Return Type of Type type is converted to an expression that has a pointer of type '' to the return type of the function.

and footnote 54) says:

Since this conversion does not occur, the operand of the sizeof operator remains the function designation and violates the restriction in 6.5.3.4.

Corresponding passage from 6.5.3.4 -

The sizeof operator does not apply to an expression that has a function type or an incomplete type

From which we can conclude that your program is called by Undefined Behavior , and no explanation can be provided for output.

+3
source

All Articles