Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function forward-declaration inside another function

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?

like image 671
Alcott Avatar asked Feb 08 '12 02:02

Alcott


2 Answers

  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).

like image 80
Ben Voigt Avatar answered Nov 14 '22 21:11

Ben Voigt


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.

like image 4
Seth Carnegie Avatar answered Nov 14 '22 19:11

Seth Carnegie