This tutorial explains the exit() function in C and how it is used.
The exit() function is useful to terminate a program after detecting an error that prevents the program from continuing to run normally. The prototype is as follows:
void exit(int status);
- Status argument passed to exit() is returned to O.S. to inform that whether or not program succeeded normally.
- Notice that this status argument is as same as status main() passes to O.S. Pre defined symbols EXIT_SUCCESS and EXIT_FAILURE are used to pass successful and failure status to O.S respectively.
- exit() function is prototyped in stdlib.h header file.
A fragment of code from stdlib.h defining EXIT_SUCCESS and EXIT_FAILURE is copied below for ref.
/* We define these the same for all machines. Changes from this to the outside world should be done in `_exit'. */ #define EXIT_FAILURE 1 /* Failing exit status. */ #define EXIT_SUCCESS 0 /* Successful exit status. */
Notice that other values could also be used to pass to exit() but their meaning is implementation dependent. It’s a good programming practice to follow calls to perror() with a call to exit().
Let’s take a simple C program to understand the behaviour of exit() function in C,
/* exit.c -- program unravels exit() behaviour */ #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *fp; /* test if file to be opened is given on command line */ if (argc == 2) { fp = fopen(argv[1], "r"); if (fp == NULL) { perror("File Open"); exit(EXIT_FAILURE); } else { printf("File: \"%s\" opened successfully!\n", argv[1]); } } else { /* if the file argument is not given or more than */ /* 2 arguments are given */ puts("Error File Argument"); exit(EXIT_FAILURE); } return 0; }
Let’s turn ours’ attention to the output below
[root@localhost ch15_Input_Output_Functions]# ./a.out preeti.txt File: "preeti.txt" opened successfully! [root@localhost ch15_Input_Output_Functions]# ./a.out Error File Argument [root@localhost ch15_Input_Output_Functions]# ./a.out preeti File Open: No such file or directory
Notice that this function never returns. When exit() function is completed, the program has disappeared and there’s nothing to return to.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Check Computer Science Books
- Check C Books
- Apply for Computer Science Internship
- Practice BCA MCQs
- Practice Computer Science MCQs