function forward-declaration inside another function

不想你离开。 提交于 2020-07-20 10:28:17

问题


Code goes first:

void foo(int x)
{
    void bar(int);  //is this forward-decl legal?
    bar(x);
}

void bar(int x)
{
    //do stuff
}

In the code above, foo calls bar, usually I put the forward-decl of bar outside of foo, like this:

void bar(int);
void foo(int x) 
{
    bar();
}

First, I think it's OK to put bar's forward-decl inside foo, right?

Second, consider this, if bar is a static function like this:

static void bar(int x)
{
    //do stuff
}

Then how should I forward-declare it? I mean should the forward-decl take or omit the static?


回答1:


  1. Yes it's legal to put a forward-declaration inside another function. Then it's only usable in that function. And the namespace of the function you put it inside will be used, so make sure that matches.

  2. The Standard says: "The linkages implied by successive declarations for a given entity shall agree." (section 7.1.2). So yes, the prototype must be static also. However, it doesn't look like putting a prototype of a static linkage function inside another function is allowed at all. "There can be no static function declarations within a block" (same section).




回答2:


Yes, it is fine to put the forward declaration inside the function. It doesn't matter where it is as long as the compiler has seen it before you call the function. You can forward-declare functions in namespaces as well. However, prototypes are limited to the scope they are in:

int blah() {
    { void foo(); }

    foo(); // error: foo not declared
}

Secondly, you only need to put static on the prototype, else the compiler will complain about bar being declared extern (all prototypes are implicitly extern unless they are explicitly marked otherwise by e.g. static). Note that static function prototypes cannot appear inside a function.



来源:https://stackoverflow.com/questions/9186996/function-forward-declaration-inside-another-function

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