The operating system (OS) is responsible for running an application program by spawning a new processes. Every process utilizes some computer resources that the OS must reclaim when the process finishes. Programs signal their termination to the OS in two ways: the return operator or the exit function. As part of its termination, the program sends or returns a single integer value, called the exit status or exit code, to the OS.
The introduction to the Hello, World! program in the previous chapter stated that "Every C++ program contains exactly one function named main." That main function, and those presented in the examples throughout the text, end with the statement return 0;. This statement doesn't seem to contribute anything to writing a message to the console or any problem solution, but its ubiquity suggests that we must understand it. Trying to describe the return operator's behavior without using the word "return" in the description is a bit awkward, but we might say that it reverts program control from a function back to its starting location. Or, simply, it returns control to the calling point.
The return operator provides programs with two services. First, it ends a function by returning control to where it was called or started. Second, it implements a mechanism that sends a value - the result of the function's operation - to the calling location. We'll learn more about functions in Chapter 6.
int main() { . . . return 0; } |
void main() { . . . } |
(a) | (b) |
The value following the return operator, "0" in this example and those appearing throughout the text, is the exit status. A zero exit status indicates that the program is terminating or ending without error; a non-zero exit status indicates that the program is terminating with an error. However, there is no correspondence between the exit value and a particular error - individual programs assign specific exit values to particular errors. (Confusingly, Windows specifies standard exit values for batch programs, but not applications.) The program returns the exit status to the operating system, where shell scripts or batch files can use it.
C++ Program | Windows Batch File | bash Shell Script |
---|---|---|
#include <iostream> using namespace std; int main() { int status; cout << "Enter an exit status: "; cin >> status; return status; } |
myprogram if %ERRORLEVEL% NEQ 0 echo Error |
#!/bin/bash ./myprogram if [ $? -ne 0 ] then echo Error fi |
The return operator only ends a program and returns an exit status when the program runs it from main. Later, we will write larger programs with more than one function, and sometimes, it will be desirable to terminate a program from within one of these other functions. A return statement in a function other than main returns control to the calling function but does not terminate the program. Programmers may call the exit function anywhere in a program, and when called, it terminates the program.