问题
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