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: