Difference between exit() and break in C/C++
- When a user wants to exit a program from this function is used.
- It is a void return type function that calls all functions registered at the exit and terminates the program.
- File buffers are flushed, streams are closed, and temporary files are deleted and hence memory is freed.
void exit(int status);
The parameters used are as follows:
- This function is generally used to come out of a loop at the instant.
- When a break statement is executed it transfers the control to the statements that follow the switch or loop.
Tabular Difference Between both the functions:
|It is a keyword||It is a pre-defined function.|
|It doesn’t require any header file as it is pre-defined in stdio.h header file in C.||It requires header file stdlib.h only for C, not for C++.|
|It terminates the loop.||It terminates the program.|
|It is often used only within the loop and switch case statement.||It is often used anywhere within the program.|
|It cannot be used as a variable name as it is a reserved word in the C language.||It is not a reserved word so, it is often used as a variable name.|
|In a C program, more than one break statement can be executed.||In a C program, just one exit function will be executed.|
value of a:10 value of a:11 value of a:12 value of a:13 value of a:14 value of a:15 The break statement executed when the value became 16
Explanation: In the above code, break terminates the while loop when the condition is satisfied and the code after the while loop will be executed after breaking the loop.
Below are C and C++ program demonstrating the use of exit():
i = 1 i = 2
Explanation: In the above code, after the exit function is executed, the program gets terminated and no code after that gets executed.