DEV Community

Lalit Kumar
Lalit Kumar

Posted on

How to exit a C++ program?

When we first started learning about programming and C++ we learnt many new things about a program. Every book says that the return statement tells the program when the program should terminate. But there are other ways also.


title: "How to exit a C++ program?"
tags: cpp

canonical_url: https://kodlogs.com/blog/1116/how-to-exit-a-c-program

Methods

In c++, you can exit a program in three ways:

  • Call the exit function
  • Call the abort function
  • Execute a return statement

Exit function

The exit function is defined in the header file. As the name suggests it terminates the program. As in return statement we have to return any valid value to exit a program, similarly, exit provides a value as argument to the OS as the return code of the program. By convention, every return code of zero i.e., return 0; defines that program completed successfully.

We can also use the literals defined in , EXIT_FAILURE and EXIT_SUCCESS. As the name suggests it indicates the success or failure of the program.

In simple words, we can say that the return statement from the main function has equivalent use as calling exit function with return value as arguments.

Abort function

The abort function is also defined in the header file. And it also terminates or exits the program.

The difference in abort and exit function is that exit function allows C++ run-time termination processing to take place whereas abort function exits the program immediately.

The abort function bypasses the normal destruction process for global static objects and also by passes any special processing that was specified using the atexit function.

Atexit function
This function is automatically called when the program exits normally.

Return statement

Calling return statement from the main function also terminates the program and it is equivalent to the exit function. C++ requires that functions have return type other than void. The return statement allows us to return a value from the main.

Note: return void and return 0 are two different things.

Example

#include <stdlib.h>
int main()
{
    exit( 3 );
    return 3;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)