What happens when non-static function declaration follows static function declaration?

我是研究僧i 提交于 2020-01-29 10:14:22

问题


The following compiles:

static int foo() { return 1; }
int foo();

But, will it always compile? Is the behavior in this case well defined? And what does it means when a non-static prototype follows a static declaration?


回答1:


Yes it will compile and behavior is well defined. Since foo is declared static earlier than int foo();1, foo has internal linkage.

C11: 6.2.2 Linkages of identifiers (p4):

For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,31)if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. [...]

and the foot note states that:

31) As specified in 6.2.1, the later declaration might hide the prior declaration.


1. If no storage class is specified , the function is assumed to have external linkage. Standard says: If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern -- 6.2.2 (p5).




回答2:


By default functions are global. So making it

static int foo() { return 1; }

The function foo() is just visible within this file. Since you just have the declaration int foo(); this is fine and well defined if you have a definition for the same int foo(){ return 2;} then you will get redefinition error.

As stated by @haccks

6.2.1, the later declaration might hide the prior declaration.

Note the difference between declaration and definition.



来源:https://stackoverflow.com/questions/28264874/what-happens-when-non-static-function-declaration-follows-static-function-declar

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