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()
C Programming: Tips of the Day
Returning an array using C
You can't return arrays from functions in C. You also can't (shouldn't) do this:
char *returnArray(char array []){ char returned [10]; //methods to pull values from array, interpret them, and then create new array return &(returned[0]); //is this correct? }
returned is created with automatic storage duration and references to it will become invalid once it leaves its declaring scope, i.e., when the function returns.
You will need to dynamically allocate the memory inside of the function or fill a preallocated buffer provided by the caller.
Dynamically allocate the memory inside of the function (caller responsible for deallocating ret)
char *foo(int count) { char *ret = malloc(count); if(!ret) return NULL; for(int i = 0; i < count; ++i) ret[i] = i; return ret; }
Call it like so:
int main() { char *p = foo(10); if(p) { // do stuff with p free(p); } return 0; }
Ref : https://bit.ly/3yFIeao
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook