w3resource

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()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
{
    ptr = 0;// oops, I meant *ptr = 0
}

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q