I am preparing some code:
for(int a = 1; a <= 100; a++) //loop a (main loop)
{
for(int b = 1000; b <= 2000; b++) //loop b
{
if(b == 1555)
break;
}
for(int c = 2001; c <= 3000; c++) //loop c
{
.
.
.
}
}
I want to break the main loop (loop variable int a) by using a break; statement in the b loop (loop variable int b).
How can I do it?
I recommend refactoring your code into a function. Then you can just
returnfrom that function instead of usingbreak:This – or perhaps even a more involved refactoring of your code – should lend itself to a clean, elegant solution. Alternatively, if you just want a quick fix you could use a condition variable:
Others have suggested using
goto. While that is another quick fix, I strongly recommend against it, especially if you are working in a rigorous environment where the code will be peer reviewed and used for years down the road.In my opinion the
gotoapproach is a bit harder to maintain than a function/return refactoring, especially later on when someone else makes changes to the code. Plus you will have to justify thegototo anyone else on the team that happens to stumble onto the code.