In this section, we will learn what the exit() function is and how it works in C.
Exit in C Programming: C exit() Function
The `exit()` function is used to end the execution of a running program.
This function can be used in any block and any function of a program and the moment the CPU reaches to this function, it will end the execution of the program immediately.
The prototype of the function exists in the `stdlib.h` header file and so we need to include the file in order to work with the function.
C exit() Function Syntax:
Here’s the prototype of the function:
void exit(int status)
C exit() Function Parameters
As you can see the function takes one argument and if the value is 0 for the function, it means the program terminated successfully without any problem and if we set a non-zero value, it means there was a problem in the program and that’s why it needed to terminate.
Notes:
- The usual values we put as the argument to this function are macros like ` EXIT_FAILURE` if we want to terminate the program because of a problem and `EXIT_SUCCESS` if the program is terminating successfully.
- The value we set as the argument of the function is sent to the underlying operating-system and that will decide what to do with this value.
C exit() Function Return Value
The return value of this function is void.
Example: using exit() function in C
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main() {
FILE *file = fopen("G:/file3.txt","r");
//if there was a problem on opening the file, exit the program.
if (file == NULL){
printf("There was a failure on opening the file.");
exit(EXIT_FAILURE);
}
char *string = "Hello,\nMy name is John Doe!\n";
for (int i = 0 ; i<strlen(string);i++){
fputc(*(string+i), file);
}
fclose(file);
printf("\ndone\n");
return 0;
}
Output:
There was a failure on opening the file.
How to End C Program?
In this example because the file named `file3.txt` didn’t exist, the call to the `fopen()` function returned NULL-pointer and for that reason the body of the `if` statement ran and as a result the call to the `exit()` function in this body caused the end of the program’s execution.