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:
Value Description EXIT_SUCCESS Successful Termination 0 Successful Termination EXIT_FAILURE Unsuccessful Termination
- 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.||It requires header file stdlib.h|
|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 can 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.|
Below is a C program demonstrating the use of break:
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 when the value became 16
Explanation: In the above code, break terminates the while loop when the if the condition is satisfied and the code hereafter while loop will be executed after breaking the loop.
Below is 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.
Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.