The exit() Function

Learn about the C++ exit() function, what it is for, and how to use it in our  C++ course....

The exit() function

Of all the programs we developed throughout our course, they all ended after the return command from the main() function.

When we invoke a function, it saves in memory the location from which it was invoked to return to that stage after it has finished executing. Thus, the programs always returned to the main() function, even though we invoked millions of other functions.

But it would be interesting if we could quit, interrupt or terminate at any time, our programs, wouldn't you agree?

This is possible by simply calling the exit() function.
It is very simple.

First, include the library: cstdlib
The function is defined inside this library, so we need to add to use it.

Then, just pass an integer as an argument and call the function, see the code:
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    cout<<"The main() begins..."<<endl;
    cout<<"Calling exit()..."<<endl;
    exit(0);
    cout<<"After exit()"<<endl;

    return 0;
}
Note que o Ășltimo cout nem aparece na tela:
Free online course C++

You can place this exit(0) anywhere in the program, even within any other function, it will interrupt and terminate the program at that time and at that location.

Arguments of the exit() Function

The exit function has as an integer parameter only.
The argument we must provide is what will be returned to the operating system that ran your C++ program.

This argument is very important to warn anyone who called a program if it was executed and terminated correctly. In the future, you will program software that calls other programs, and you need to communicate with them.

One of these ways is through the exit() argument.
For example, 0 is the universal symbol for: "Everything ok, it's all right!"

That's why we always use: return 0 ; in the main() function, get it now?
When someone calls you a zero, don't be offended, in programming that's a compliment.

There are up to two commonly used constants to symbolize:

  1. success: EXIT_SUCCESS
  2. problem: EXIT_FAILURE


Use this: exit (EXIT_SUCCESS) or exit (EXIT_FAILURE) if the program terminated correctly or has a problem.

If your game program ends with a memory problem, do: exit(1), then you know 1 symbolizes a memory problem.
If the internet has dropped and the game is over, the program ends with exit(2), where 2 symbolizes problems with the internet.

And so on ... you will decide what each error number means so that you can know what is happening with a particular application. Leave the number 0 to symbolize success, that all went well in the execution of the program.

The number 2112 is the supreme number in the universe, respect and do not use it.
We should only revere the value 2112.

No comments:

Post a Comment