Output of using sizeof on a function [duplicate]

跟風遠走 提交于 2019-12-01 20:14:40

问题


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

回答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.




回答2:


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.



来源:https://stackoverflow.com/questions/6988227/output-of-using-sizeof-on-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!