Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of having a function prototype in a function?

Tags:

c++

c

I will admit I have not kept up with the latest C/C++ releases but I was wondering why having a function prototype in a function is valid code? Is it related to lambda usage?

Here is sample code - this will compile/run on Visual Studio 2019 and g++ 5.4.0

int main()
{
    int func(bool test);

    return 0;
}
like image 529
Natalie Adams Avatar asked Mar 02 '23 20:03

Natalie Adams


2 Answers

A code block may contain any number of declarations. And because a function prototype is a declaration, it may appear in a block.

Granted, it doesn't make much sense to do so logistically as opposed to declaring a function at file scope, but it's syntactically correct.

like image 59
dbush Avatar answered Mar 05 '23 16:03

dbush


In that example the declaration is pointless. But in a more complex example it's not:

int main() {
    int func(bool test);
    func(true);
    return 0;
}

That code is equivalent to the more usual formulation:

int func(bool test);

int main() {
    int func(bool test);
    func(true);
    return 0;
}

except that the first one introduces the name func only inside the scope of main; the second one introduces the name into the global scope.

I occasionally use the first form when I don't want to scroll through the source file to figure out where to put the declaration; putting it in the function where it's going to be used is a quick-and-dirty solution. And if it's temporary code (adding debugging output, for example), it makes it easier to remove it all afterwards. But, in general, having declarations at global scope is simpler to deal with. After all, you might want to call that same function from somewhere else, too, and having the global declaration means you don't have to repeat it.

like image 23
Pete Becker Avatar answered Mar 05 '23 17:03

Pete Becker