+ 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?
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
+ 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. 😉
+ 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.
+ 5
it's all depend on ur program if it is necessary then u have to