exit
The
exit function allows stopping the execution of a program. It takes an
int as an argument, which is
returned by the current process to the one which generated it.
The loop in the program below, for example, iterates – asking for
numbers from the user and returning their squares – until
number is
equal to 0. At that point the program is exited. The exit code
EXIT_SUCCESS is equivalent to 0.
The alternative is
EXIT_FAILURE
(non-zero).
Example
#include <iostream>
using namespace std;
// exit(): standard library function
int main()
{
while(1)
{
int number;
cout << "Enter number: ";
cin >> number;
if(!number)
exit(EXIT_SUCCESS); // exits with 0 as return value. Alternative: EXIT_FAILURE
cout <<"The square is: " << number * number << endl << endl;
}
}
(Possible) Output
Enter number: 3
The square is: 9
Enter number: 7
The square is: 49
Enter number: 0