Monday, May 24, 2010

In c language whenever if we want to make an exit from a loop why do we write inside the loop as exit(0);?

First: do not exit from the loop with exit(0). This will exit from your program.


Second: you can exit a loop by using break;





example1





#include %26lt;stdio.h%26gt;





int main(void)


{


int i=0;


while (1) // an infinite loop


{


i++;


printf("%d ",i);


if (i==7)


break; // not exit(0)


}


return 0;


}





But please create only


conditional loops:





while (i!=7)


{


i++;


printf("%d ",i);


}


In this case the loop will


exit when i==7





About the exit(0) function.


This will terminate your program.


Use it only when you have some


problems and you can't do


anything to solve them:





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;





int main(void)


{


int i=5;


myerror(5);


return 0;


}


int myerror(int i)


{


if (i==5){


printf("Oups!\n");


printf("I must exit!\n");


exit(EXIT_FAILURE);


//better than exit(0);


} // from if


return 0;


}








I hope this will help u.

In c language whenever if we want to make an exit from a loop why do we write inside the loop as exit(0);?
It is very rare to use exit(). Generally, you would use that function to immediately terminate the program. The program will exit differently, than if you exited a program with something like, 'return 0;'


If you want to exit out of a program normally, use something like 'return %26lt;int%26gt;'.





Hint on loops:


You use a 'for' loop if you know the number of iterations that the loop will make.


There is very little reason to have to forcibly exit out of a 'for' loop.





You use a 'while' loop if you don't know how many times a loop will execute. As the word 'while' hints at, a While loop will execute until a variable has changed to meet a certain condition, such as 'while (a%26lt;15)'
Reply:use: break;, exit(0) only for progam exit
Reply:Use that when you want to exit the loop from inside. It is not necessary if the loop exits at the end normally. Use it only for an abnormal loop ending.





Setting exit(1) would be used if this is an error detection of some sort.





In fact, good coding means that you do not work a loop exit from the middle. Always design around using a technique that tests for all possible end conditions as a part of the loop structure. You see, these weird loop exits become hard for others to understand.
Reply:in c programming language


we need to write exit(0);


because 'o' refer to a function called in a loop


and exit mean to go out of a function


and ; mean end of a statement


No comments:

Post a Comment