exit(), abort() and assert() in C/C++


exit()

The function exit() is used to terminate the calling function immediately without executing further processes. As exit() function calls, it terminates processes. It is declared in “stdlib.h” header file. It does not return anything.

Here is the syntax of exit() in C language,

void exit(int status_value);

Here,

status_value − The value which is returned to parent process.

Here is an example of exit() in C language,

Example

 Live Demo

#include <stdio.h>
#include <stdlib.h>
int main() {
   int x = 10;
   printf("The value of x : %d\n", x);
   exit(0);
   printf("Calling of exit()");
   return 0;
}

Output

The value of x : 10

In the above program, a variable ‘x’ is initialized with a value. The value of variable is printed and exit() function is called. As exit() is called, it exits the execution immediately and it does not print the printf(). The calling of exit() is as follows −

int x = 10;
printf("The value of x : %d\n", x);
exit(0)

abort()

The function abort() terminates the execution abnormally. It is suggested to not to use this function for termination. It is declared in “stdlib.h” header file.

Here is the syntax of abort() in C language,

void abort(void);

Here is an example of abort() in C language,

Example

 Live Demo

#include <stdio.h>
#include <stdlib.h>
int main() {
   int a = 15;
   printf("The value of a : %d\n", a);
   abort();
   printf("Calling of abort()");
   return 0;
}

Here is the output,

Output

The value of a : 15

In the above program, a variable ‘a’ is initialized with the value and printed. As the abort() is called, it terminates the execution immediately but abnormally. The calling of abort() is as follows.

int a = 15;
printf("The value of a : %d\n", a);
abort();

assert()

The function assert() is declared in “assert.h” header file. It evaluates the expressions given as argument. If expression is true, it does nothing. If expression is false, it abort the execution.

Here is the syntax of assert() in C language,

void assert(int exp);

Here.

exp − The expression you want to evaluate.

Here is an example of assert() in C language,

Example

 Live Demo

#include <stdio.h>
#include <assert.h>
int main() {
   int a = 15;
   printf("The value of a : %d\n", a);
   assert(a!=15);
   printf("Calling of assert()");
   return 0;
}

Output

The value of a : 15
main: main.c:9: main: Assertion `a!=15' failed.

In the above program, a variable ‘a’ is initialized with a value. The value of variable is printed and assert() function is called. As assert() is called, it evaluates the expression that ‘a’ is not equal to 15 which is false that is why it aborts the execution and shows an error.

int a = 15;
printf("The value of a : %d\n", a);
assert(a!=15);

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements