Ad

Alternative While Loop Without Break

- 1 answer

    int number = 0;

   while (scanf("%d",&number)){

       if (sayi == 1 || sayi == 2){
           printf("Login succesful ");
           break;
       }


    }

How can I write this code without break?

Ad

Answer

A break is better here. It more closely hints at the more optimal assembly output. But you can always use another variable (BTW, your error checking of scanf is wrong).

int number = 0;
_Bool not_broken=1;
while (not_broken){
   if (1!=scanf("%d",&number)) {/*handle error*/}

   if (number == 1 || number == 2){
       printf("Login succesful ");
       not_broken = 0;
   }
}

I'd recommend against trying to stuff everything into the while condition. It's less readable and even if a scanf failure ultimate results in a jump out of the loop (e.g., if you have not_broken=0 in the /*handle error*/ part), you'll still usually want to do something different in response to an error than in response to different inputted choices. The separate if is a cleaner way towards providing such separate responses.

(I have also taken the liberty to change sayi to number because using an unrelated variable there seemed like a coding error.)

Ad
source: stackoverflow.com
Ad