开发者

What are the differences between break and exit?

开发者 https://www.devze.com 2022-12-24 08:39 出处:网络
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 开发者_StackOverflowexplain with small examp

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 开发者_StackOverflowexplain with small example. Thank you.


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().


break is a control flow statement of the language. It says that next statement to be executed is the one at the end of the loop (or at the end of the switch statement)

 while (...) {  /* same for "do {} while" or "for" */ 
   ... 
   break;  -----+    
   ...          |  
 }              |
 ....       <---+  JUMP HERE!



 switch (...) {
   ... 
   break;  -----+    
   ...          |  
 }              |
 ....       <---+  JUMP HERE!

exit(), instead, is a function that says that the program must end and control must be given back to the operating system. Depending on the Operating System, on exit, there are many things that happen behind the scenes to clean up and release the resources used. You can also use the atexit() function (in C99) to define a function to be called before exiting.


break is used to exit from the loop.

exit is used to exit from the program.

#include<stdio.h>
#include<stdlib.h>
main()
{
        int d;
        while(1)
        {
        scanf("%d",&d);
        if(d==1)
        {
                break;
        }
        else if(d==4)
        {
                exit(0);
        }
        }
        printf("WELCOME YOU MATCH BREAK\n");
}

If you press the 1, it will exit from the loop. Not from the program. So that time it will print the string.

If you press 4, it will exit from the program, It will not print the string.

0

精彩评论

暂无评论...
验证码 换一张
取 消