+ 5

Is using break statement in loops discouraged?

my teacher says that using a break statement in any loop(for, while, do/while) is bad, but I don't see why. Is there any reason why he might say that?

29th Jan 2018, 10:26 AM
Asim Maredia
4 Respuestas
+ 17
sometimes it better to use break; to avoid unnecessary running of loop for example ... u want to calculate whether no. is prime or not initially , initialize a boolean variable as true ... run a loop from x=2 to n/2 //if number gets divisible then just change value of boolean to false & break ... else move to check for x+1 //break; is bad in examples like given by Jacob
29th Jan 2018, 11:03 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 14
I'm not sure about that as it depends on the context and it would be helpful if your teacher provides an example. In programming, there might be only a few ways to do the same thing but plenty of ways to do it wrong. In this case, it's not to say that the result is wrong, but the approach. You may Google "code anti-pattern" for more info if you're interested. 😉
29th Jan 2018, 11:08 AM
Zephyr Koo
Zephyr Koo - avatar
+ 7
He/She might mean only when you don’t need to. For example: int a = 0; while (a < 5) { cout << a << endl; a++; } Would be better than: int a = 0; while (true) { cout << a << endl; a++; if (a < 5) break; } If you actually have a reason to use break, there is no problem with it though.
29th Jan 2018, 10:53 AM
Jacob Pembleton
Jacob Pembleton - avatar
+ 5
it's all depend on ur program if it is necessary then u have to
29th Jan 2018, 10:57 AM
fahim