
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Exit vs Exit in C/C++
In C/C++, both exit() and _Exit() are used to terminate a program. The exit() performs cleanup like flushing output, closing files, and calling functions, while _Exit() ends the program immediately without doing any cleanup.
Now, let us learn the difference between exit() and _Exit() individually in C/C++.
C++ exit() Function
The exit() function is used to clean up before terminating the program. It calls functions registered with atexit(), flushes file buffers, and returns control to the operating system.
Syntax
Following is the syntax for exit() function:
void exit(int status_value);
Example
In this example, we print "Program is running..." and then terminates using exit(0) by performing cleanup and preventing the last 'cout' statement from executing.
#include<stdio.h> #include<stdlib.h> // For exit() int main() { printf("Program is running...\n"); exit(0); // Program terminates and performs cleanup printf("This won't be printed.\n"); return 0; }
Following is the output to the above program:
Program is running...
#include<iostream> #include<cstdlib> using namespace std; int main() { cout<<"Program is running..."<<endl; exit(0); // Program terminates and performs cleanup cout<<"This won't be printed."<<endl; return 0; }
Following is the output to the above program:
Program is running...
C++ _Exit() Function
The _Exit() function is used to terminate the program immediately without performing cleanup tasks. It does not call atexit() functions or flush file buffers; it simply stops execution.
Syntax
Following is the syntax to the _Exit() function.
void _Exit(int status_value);
Example
In this example, we print "Program starts..." and then immediately terminates using '_Exit(0)' by skipping cleanup tasks and preventing the last 'cout' statement from executing.
#include<stdio.h> #include<stdlib.h> int main() { printf("Program starts...\n"); fflush(stdout); // Ensures the output is printed before termination _Exit(0); // Immediate termination without cleanup printf("This won't be printed either.\n"); return 0; }
Following is the output to the above program:
Program starts...
#include<iostream> #include<cstdlib> using namespace std; int main() { cout<<"Program starts..."<<endl; _Exit(0); // Immediate termination without cleanup cout<<"This won't be printed either."<<endl; return 0; }
Following is the output to the above program:
Program starts...