The exit() Function
There is also a C library function, exit(), that can be used to cause a program to end. Because the exit() function is defined in a header file, stdlib.h, you have to include the header file at the beginning of your program।
Unlike main(), the exit() function itself does not return any values, but the argument to exit() indicates whether the program is terminated normally. A nonzero argument to the exit() function tells the operating system that the program has terminated abnormally.
Actually, you can replace return 0; in line 7 of Listing 2.1 with exit(0); and get a similar result after running the modified program.
Note that return and exit() can also be used in other functions. You'll see more examples in the rest of the book.
Listing 2.2 contains the program that uses exit() instead of return.
TYPE
Listing 2.2. A C program with exit().
/* 02L02.c */
#include <stdlib.h>
#include <stdio.h>
void main()
{
printf ("Howdy, neighbor! This is my first C program.\n");
exit(0);
}
After compiling the program in Listing 2.2, you should be able to run the program and get the same message, Howdy, neighbor! This is my first C program., printed out on the screen.
- 39 views