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
?
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With