how do i repeat the whole program (my style)

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(); 
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); }
am i considered a criminal?
No, haha, but your example is wrong.
wwhy is it illegal
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
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
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.