Even I used break() and exit() statements many times, I am bit confused between them. I need to know exact meaning of both, when we should use them. Please explain with small example. Thank you.
A "break" is only allowed in a loop (while or for), and it causes the loop to end but the rest of the program continues. On the other hand "sys. exit()" aborts the execution of the current program and passes control to the environment.
The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program.
return is a statement that returns the control of the flow of execution to the function which is calling. Exit statement terminates the program at the point it is used.
In the C programming language, there are times when you'll want to change looping behavior. And the continue and the break statements help you skip iterations, and exit from loops under certain conditions.
break
is a keyword that exits the current construct like loops. exit
is a non-returning
function that returns the control to the operating system. For example:
// some code (1)
while(true)
{
...
if(something)
break;
}
// some code (2)
In the above code, break exits the current loop which is the while loop. i.e. some code (2) shall be executed after breaking the loop.
For exit, it just gets out of the program totally:
// some code (1)
while(true)
{
...
if(something)
exit(0);
}
// some code (2)
You would get out of the program. i.e. some code (2) is not reached in the case of exit().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With