Lesson 77 +10 XP

Halts (Exiting Early)

Halts (Exiting Early)

Sometimes a program must stop before reaching the end of main. Two common ways are std::exit and an early return.

return from main

A return inside main ends the program immediately. The value you return is the exit status handed back to the operating system.

#include <iostream>
using namespace std;

int main() {
  cout << "starting" << endl;
  return 0;   // stop here, status 0
  cout << "never runs" << endl;
}

std::exit

std::exit(status) stops the program from anywhere, even deep inside another function. It is declared in the <cstdlib> header.

#include <cstdlib>
#include <iostream>
using namespace std;

int main() {
  cout << "about to stop" << endl;
  exit(0);    // stop with status 0
  cout << "never runs" << endl;
}

What the exit status means

The status is a small code the operating system reads. By convention, 0 means all is well, and any non-zero value means something went wrong. LearnCpp 8.12 notes that while exit works anywhere, an early return is often the cleaner choice in main.

TL;DR

  • return 0; in main ends the program with status 0.
  • std::exit(status) halts the program from anywhere.
  • std::exit lives in the <cstdlib> header.
  • Status 0 means success; non-zero means an error.