c++functionnested

Nested functions are not allowed but why nested function prototypes are allowed? [C++]


I was reading the linked question which leads me to ask this question.

Consider the following code

int main()
{
    string SomeString();
}

All says, compiler takes this as a function prototype and not as a string object. Now consider the following code.

int main()
{
    string Some()
    {
        return "";
    }
}

Compiler said this is invalid as I guess nested function definition is not allowed. If it is not allowed, why nested function prototypes are allowed? It is not giving any advantage rather than making confusion (or am I missing some valid points here?).

I figured out the following is valid.

int main()
{ 
  string SomeFun();
  SomeFun();
  return 0;
}

string SomeFun()
{
  std::cout << "WOW this is unexpected" << std::endl;
}

This is also confusing. I was expecting the function SomeFun() will have a scope only in main. But I was wrong. Why compiler is allowing to compile code like the above? Is there any real time situations where code like the above makes sense?

Any thoughts?


Solution

  • Your prototype is just 'Forward Declaration'. Please check out the Wikipedia article.

    Basically, it tells the compiler "don't be alarmed if the label 'SomeFun' is used in this way". But your linker is what's responsible for finding the correct function body.

    You can actually declare a bogus prototype, e.g. 'char SomeFun()' and use it all over your main. You will only get an error when your linker tries to find the body of your bogus function. But your compiler will be cool with it.

    There are lots of benefits. You have to remember the function body is not always in the same source code file. It can be in a linked library.Also, that linked library may be have a specific 'link signature'.Use conditional defines you may even select the correct link signature at build time using your scoped prototypes.Although most people would use function pointers for that instead.

    Hope this helps.