C++: declaration of a function inside another function is not a compiler error so… what is it?

本秂侑毒 提交于 2021-02-05 07:51:31

问题


Accidentally I compiled a source similar to this:

//void y(); //optionally declaring y()

void x()
{
  //some code...
  void y();
  //some code...
}

//void y() {/*some code*/} //optionally defining y()

This was compiled with VS 2017 and also two clang versions. None of these compilers complained about this source code – no errors, no warnings. There was a typo in my code – in this example, there should be no void in front of y() and therefore y() was supposed to be called, so it was a rather sneaky bug with no visible consequences while compiling.

I was curious what the compiler was thinking. Trying to debug the code, the void y(); line inside x() was inaccessible, so seems like no actual machine code was produced. I tested this with the void y() {/*somecode*/} function declared above and defined below x() and also with no such function – no difference.

Did the compilers consider this a declaration? if so, how this could be further used when defining a function within a function this way (not speaking about lambdas) is not allowed in C++? I assume that if such a declaration is valid inside a function, it would mostly make sense if one wanted to define a function inside x() as well, otherwise the declaration of y() could be moved outside and above x().

EDIT: Related discussions and explanations:

  • Function declaration inside of function — why?
  • Syntactic ambiguity — most vexing parse

回答1:


I was curious what the compiler was thinking.

Its thinking that you declared a function by the name y that returns void and has an empty argument list. void y(); is a function declaration.

Did the compiler(s) consider this a declaration?

Yes.

if so, how this could be further used when nested functions are not allowed in C++?

You can use a function declaration for example to call it, or to take its address. Like so:

void x()
{
    void y(); // a function declaration

    // now that y has been declared, it can be called:
    y();      // a function call

    // also, it is now possible to take the address:
    void (*fun_ptr)() = y;
}


来源:https://stackoverflow.com/questions/57129750/c-declaration-of-a-function-inside-another-function-is-not-a-compiler-error-s

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