Reputation: 124
I want to get rid of this goto
statement. Can any one tell me the logic for the same. The code below is not the exact code that I want to modify, but it will support my question. Please don't ask the significance of the code when commenting on this post as it is just an example.
int result[i][j];
for (int i = 0; i<100; i++)
{
for (j = 0; j<100; j++)
{
result[i][j] = j++;
if (j == 80)
goto break1;
}
}
break1:
…;
Upvotes: 4
Views: 1546
Reputation: 28837
int result[i][j];
for (int i = 0; i<100; i++)
{
for (j = 0; j<100; j++)
{
result[i][j] = j++;
if (j == 80)
{
i = 100;
break;
}
}
}
The break statement breaks out of the inner loop. Setting i to 100, causes the outer loop to finish.
Upvotes: 0
Reputation: 1
int result[i][j];
for (int i = 0; i<100; i++)
{
int j;
for (j = 0; j<100; j++)
{
result[i][j] = j++;
if (j == 80)break;
}
if(j == 80) break;
}
Know this is an old question but can be modified simply
Upvotes: 0
Reputation: 15357
Use a boolean to break from the for loop(s).
int result[i][j];
bool cont = 1;
for (int i =0;i<100;i++)
{
for(j = 0;j<100;j++)
{
result[i][j] = j++;
if(j == 80)
{
cont = 0;
break;
}
}
if (cont == 0)
break;
}
break1;
(note: not tested on real compiler).
Upvotes: 1
Reputation: 50053
Put those loops in a function, give it a proper name and return;
when it is done. If it is complicated enough to need two loops, it deserves a name.
A finished flag is so hard to read that you should put that construct in its own function anyway, making it obsolete.
Exceptions are only for errors you cannot handle locally. Use them to notify higher level functions that something you cannot fix went wrong, not if something that was supposed to happen happened.
Upvotes: 4
Reputation: 108978
I sometimes like changing the control variable(s)
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
/* work */
if (j == 80) i = j = 100; // 100 makes both loops terminate
}
}
Upvotes: 0
Reputation: 69663
I would see three possible solutions.
return
Upvotes: 2
Reputation: 1312
Since you want to break two loops, you have to notify the outer loop. You can do this by having a boolean that checks for that:
bool break_loop = false;
for (int i = 0; i < 100; ++i) {
for (int j = 0; j < 100; ++j) {
if (j == 80) {
break_loop = true;
break;
}
}
if (break_loop) break;
}
Upvotes: 1