How to exit program execution in C++?

Which function is used in C++ stdlib to exit from program execution with status code?

In Java, there’s:

System.exit(0)

Answer

Assuming you only have one thread:

#include <iostream>

int main()
{
    std::cout << "Hello, World!n";

    return(0);
    // PROGRAM ENDS HERE.

    std::cout << "You should not see this.n";

    return(0);
}

Output:

Hello, World!

The return(0); can be placed anywhere you like – it’ll end int main(), and hence your program.


Alternatively, you can call exit(EXIT_SUCCESS); or exit(EXIT_FAILURE); from anywhere you like:

/* exit example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
    FILE * pFile;
    pFile = fopen("myfile.txt", "r");

    if(pFile == NULL)
    {
        printf("Error opening file");
        exit (1);
    }
    else
    {
        /* file operations here */
    }

    return 0;
}