how do i repeat the whole program (my style)

Mar 16, 2017 at 6:02pm
Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
this is my style to repeat program

int repeat;
cout << "continue: type 1 or to exit type 0: ";
cin>>repeat;

if (repeat != 0)
{
main();
}

// main() continues but it doesnt close the previous program
//i want to do something like main().close(); 
Mar 16, 2017 at 6:09pm
It is illegal to invoke the main function in C++.

It's unclear what you mean by "close the previous program"... a program cannot restart itself after it has terminated.

Why is a loop not acceptable?
int main() { bool repeat = false; do { /* your code here */ } while (repeat); }
Mar 16, 2017 at 6:24pm
am i considered a criminal?
Mar 16, 2017 at 6:29pm
No, haha, but your example is wrong.
Mar 16, 2017 at 6:30pm
wwhy is it illegal
Mar 16, 2017 at 6:30pm
Hello seungyeon,

As mbozzi said Why is a loop not acceptable?

Same thing different format:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//  Header files here
#include <iostream>

int main()
{
	bool repeat{ true };  // <--- No need for a globl variable.

	do
	{
		/*
		  your code here
		*/

		cout << "continue: type 1 or to exit type 0: ";
		cin >> repeat;

	} while (repeat);

	return 0;
}


Hope that helps,

Andy
Mar 16, 2017 at 6:43pm
Why is it illegal

Because the International Standard says:
6.6.1.3 [basic.start.main]:
The function main shall not be used within a program. ...

http://eel.is/c++draft/basic.start.main#3

I know it's unsatisfying to get an answer "because they said so", but the ISO/IEC international committee's rationale is a consequence of long-standing convention and the other requirements imposed (or not imposed) upon the main function and the implementation.
Last edited on Mar 16, 2017 at 6:46pm
Mar 16, 2017 at 6:57pm
While I personally detest using recursion in this way, you could create your own function and then have that function call itself.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void myfunc ()
{   //  Some code
    int repeat;
    cout << "continue: type 1 or to exit type 0: ";
    cin>>repeat;

    if (repeat != 0)
    {   myfunc();
    }
}

int main ()
{   myfunc ();
    return 0;
}


The reason I detest using recursion in this manner is that every time you repeat the code, your add another stack frame to the stack. If the code is repeated enough times, you could run out of stack space. You can avoid this, as others have said, by using a conventional loop.
Topic archived. No new replies allowed.