Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is return main(); a valid syntax?

I found some interesting code lines:

#include <stdio.h>

int main()
{
    printf("Hi there");
    return main();
}

It compiles OK (VS2013) and ends up in stackoverflow error because of the recursive call to main(). I didn't know that the return statement accepts any parameter that can be evaluated to the expected return data type, in this example even int main().

Standard C or Microsoft-ish behaviour?

like image 478
Pottwal Ahab Avatar asked Jul 25 '26 23:07

Pottwal Ahab


2 Answers

I didn't know that the return statement accepts any parameter that can be evaluated to the expected return data type,

Well, a return statement can have an expression.

Quoting C11 standard, chapter 6.8.6.4, The return statement.

If a return statement with an expression is executed, the value of the expression is returned to the caller as the value of the function call expression.

so, in case of return main();, the main(); function call is the expression.

And regarding the behaviour of return main();, this behaves like a normal recursive function, the exception being an infinite recursion in this case.

Standard C or Microsoft-ish behaviour?

As long as C standard is considered, it does not impose any restriction upon calling main() recursively.

However, FWIW, AFAIK, in C++, it is not allowed.

like image 199
Sourav Ghosh Avatar answered Jul 27 '26 14:07

Sourav Ghosh


In C, main can be called like any other function for example in a return statement like in your program.

Calling main recursively is allowed as it is with other functions, there is no special restriction:

(C11, 6.5.2.2p11) "Recursive function calls shall be permitted, both directly and indirectly through any chain of other functions."

In C++, it is not allowed to call main, so the function cannot be called in a return statement.

(C++11, 3.6.1p3) "The function main shall not be used within a program"

like image 22
ouah Avatar answered Jul 27 '26 14:07

ouah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!