Exiting while(1) loop in C programming

  • A+
Category:Languages

I am doing examples for my C programming class. And one of the examples is this:

Update: Difference between return 0; and break;

#include<stdio.h> int main() {  while(1) {   printf("Enter number: ");   scanf("%d", &num);    if (num==2)    {       return 0;    }   else    {       printf("Num = %d", num);    }  return 0; } 

I know that while(1)is an infinite loop. To get out of loop I used break;normally.

But, in this example when num=2 it gets out of loop.

I don't understand how return o; effects the while(1) loop ?


To better explain to you lets add few lines to your code:

#include<stdio.h> int main() {      while(1)     {         printf("Enter number: ");         scanf("%d", &num);          if (num==2)         {             return 0;         }         else         {             printf("Num = %d", num);         }      }       printf ("BYE/n");      return 0; } 

and lets put break instead of return 0;:

#include<stdio.h> int main() {      while(1)     {         printf("Enter number: ");         scanf("%d", &num);          if (num==2)         {             break;         }         else         {             printf("Num = %d", num);         }      }       printf ("BYE/n");      return 0; } 

Output of first code would not include the message "BYE", where second code would.

So the to sum up return terminates function and does not execute anything below it, where break terminates loop and program does not execute remaining lines with in the loop.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: