First of all, during this post keep in mind that when I am referring to a program or a code it means that the program is only able to do 1 thing or function or whatever you want to call it, thanks.
Is it possible to program any recursive function on main?
If so, I would like someone to post the solution to the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int operation () {
char c;
cin >> c;
if (c == '+') return operation() + operation();
if (c == '-') return operation() - operation();
if (c == '*') return operation() * operation();
elsereturn c - '0';
}
int main () {
cout << operation() << endl;
}
Is it recommended to use recursion on main or is it better to create a function for it?
The following 2 examples illustrate this case:
Example using recursion on a function.
- Less efficient
- More maneuverability and adaptability
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
void turn () {
string word;
if (cin >> word and word != "end") {
turn ();
cout << word << endl;
}
}
int main () {
turn ();
}
No, calling main() in a C++ program is specifically not allowed by the C++ standard. Also, IMO, you should prefer iteration over recursion in most cases.
> g++ allowed it, lol. I thought it might so I tried it. Its always been a little off.
The GNU compiler is always a little off (everywhere) unless we explicitly demand conformance to the C++ standard.
-std=c++14 treat this this program as a C++ program; it is not a gnu++ program -pedantic-errors Unfortunately, it wont believe you unless you also say that you were not joking when you said C++
It is one of the ways of getting a stack overflow. A typical program puts it's data on the stack - there is limited room there. Recursively calling main, keeps adding a new frame to the stack, eventually causing the overflow.
And don't forget that main() is a special function that can call other "invisible" functions that preform startup duties, like setting up the standard input output streams and perhaps may even re-setup non-local variables, etc..
1
3.6 Start and termination [basic.start]
3.6.1 Main function [basic.start.main]
A program shall contain a global function called main, which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a main function. [ Note: In a freestanding environment, start-up and termination is implementation-defined; start-up contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration. — end note ]
Even in C, which doesn't specifically disallow recursively calling main(), the practice is discouraged.