The exit() is a method or function used in C and C++ programming languages in order to exit from the current execution. The exit()generally used to end the current application and program by providing some state information to the caller.
exit() Syntax
The exit() has the following syntax where it can accept single parameter which is the status code as integer and returned to the caller.
exit(CODE)
- CODE is the integer representation of the status and returned to the caller. This is required.
exit(0)
The exit() method may return different values. The exit(0) is returned with the exit() function in order to indicate that the application executed and terminated successfully. There is no problem with the application execution. Simply use exit(0) at the termination point of the application which is generally located in the main method bottom.
Alternatively, C provides the EXIT_SUCCESS in order to use a more readable and standard way to provide status information about applications. The exit(EXIT_SUCCESS) can be used to return the successful termination of the application.
exit(1)
The exit(1) is returned in order to express that the application is terminated unsuccessfully. There are some problems with application execution. But the exit(1) is not portable which can be changed in different platforms like Windows etc. The EXIT_FAILURE can be used to express unsuccessfully termination like exit(EXIT_FAILURE) like below.
exit(0) Success Example
The exit() method can be in different cases in order to terminate application execution. One of the most popular usages is using the exit(0) in the main() method of the application. Ther
#include <stdio.h>
int main()
{
int age=37;
printf("I am %i years old.",age);
// EXIT_SUCCESS
exit(0);
}
exit(1) Failure Example
The exit(1) is generally used for failure situations like below. Below we try to open a file that fails and we use the exit(1) in order provide some operation and the execution of the application failed.
#include <file.h>
#include <stdio.h>
int main()
{
FILE* myfile;
// open the file named myfile in read-only mode
myfile = fopen("myFile.txt", "r");
if (myfile == NULL) {
printf("There is an error in opening file");
// EXIT_FAILURE
exit(1);
}
// EXIT_SUCCESS
exit(0);
}
Alternatively the exit(EXIT_SUCCESS) and exit(EXIT_FAILURE) can be used according to the exit(0) and exit(1).
#include <file.h>
#include <stdio.h>
int main()
{
FILE* myfile;
// open the file named myfile in read-only mode
myfile = fopen("myFile.txt", "r");
if (myfile == NULL) {
printf("There is an error in opening file");
// EXIT_FAILURE
exit(EXIT_FAILURE);
}
// EXIT_SUCCESS
exit(EXIT_SUCCESS);
}