Return main (); valid syntax?
I found some interesting lines of code:
#include <stdio.h>
int main()
{
printf("Hi there");
return main();
}
It compiles OK (VS2013) and ends up with stackoverflow error due to recursive call main()
. I didn't know that the operator return
takes any parameter that can be evaluated for the expected return data type, in this example even int main()
.
Standard C behavior or Microsoft-ish?
source to share
I didn't know that the return statement takes any parameter that can be evaluated for the expected return type,
Well, an operator return
can have an expression.
Quote C11
standard, chapter 6.8.6.4, Operator return
.
If a statement is executed
return
with an expression, the value of the expression is returned to the caller as the value of the function call expression.
so in case return main();
the function call main();
is an expression.
And in terms of behavior, return main();
this behaves like a normal recursive function, the exception is infinite recursion in this case.
Standard behavior
C
or Microsoft-ish?
While the standard is under review C
, it does not impose any restrictions when called main()
recursively.
However FWIW, AFAIK, in C++
, this is not permitted.
source to share
In C, main
you can call it like any other function, for example, in a return statement, as in your program.
Calling is main
recursively allowed, as with other functions, there is no special limitation:
(C11, 6.5.2.2p11) "Recursive function calls must be allowed both directly and indirectly through any other function chain."
In C ++ it is not allowed to be called main
, so the function cannot be called in a return statement.
(C ++ 11, 3.6.1p3) "The main function must not be used in the program"
source to share