C exit() function
C exit() function - Terminate a process
The exit() function is used to return control to the host environment from the program.
Syntax exit() function
void exit(int status)
Parameters exit() function
Name | Description | Required /Optional |
---|---|---|
status | Exit status code. | Required |
Return value from exit()
- This function does not return any value.
Example - 1: exit() function
The following example shows the usage of exit() function.
#include <stdio.h>
#include <stdlib.h>
FILE *stream;
int main(void)
{
printf("Exit when i = 7");
for(int i =0; i<=10; i++)
{
printf("\ni = %d",i);
if (i ==7)
exit(1);
}
}
Output:
Exit when i = 7 i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7
Example - 2: exit() function
In this example, the program ends after deleting buffers and closing any open files if it is unable to open the file 'test.txt'.
#include <stdio.h>
#include <stdlib.h>
FILE *stream;
int main(void)
{
if ((stream = fopen("user/test.txt", "r")) == NULL)
{
perror("Could not open data file! ");
exit(EXIT_FAILURE);
}
}
Output:
Could not open data file! : No such file or directory
C Programming Code Editor:
Previous C Programming: C atexit()
Next C Programming: C getenv()
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/c-programming/stdlib/c-exit.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics