+ 1

Is it possible to use break statement under if where if is a part of for loop?

I used break with if. It shows error, and with the condition as given in the question, it works.

22nd Oct 2016, 8:28 PM
Jaya
6 Answers
+ 7
Oh, I think I see your problem. In order to use a break, it HAS to be within a loop of some kind. If you use an if statement that isn't within a loop (while, for, do while) then it will give you an error, because there is nothing to "break" out of. If you have something like this: int main() { int foo = 8; if (foo == 8) break;//error. break is not within a loop return 0; }
22nd Oct 2016, 8:50 PM
Zeke Williams
Zeke Williams - avatar
+ 5
absolutely. for (i = 0; i < 10; i++) { int count = i *2; if (count == 8) break; }//this will break out of the for loop when i is equal to 4 is this what you're talking about? If not, post your code.
22nd Oct 2016, 8:33 PM
Zeke Williams
Zeke Williams - avatar
+ 1
Yes but how?
22nd Oct 2016, 8:35 PM
Jaya
+ 1
I gave you the code; that is how you can do it. Post your code, maybe there is some other issue you don't realize is happening.
22nd Oct 2016, 8:37 PM
Zeke Williams
Zeke Williams - avatar
+ 1
my code is similar to this one. I want to know how come breaks only works for If under for loop and not for if alone.
22nd Oct 2016, 8:45 PM
Jaya
+ 1
oh got it. Thanks 😊
22nd Oct 2016, 8:53 PM
Jaya