Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rid of goto statement from embedded C/C++ logic

Tags:

c++

c

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:
…;
like image 879
studinstru Avatar asked Feb 11 '23 18:02

studinstru


2 Answers

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.

like image 110
Baum mit Augen Avatar answered Feb 13 '23 07:02

Baum mit Augen


I would see three possible solutions.

  1. Put the code into a function and leave that function with return
  2. Use a "finished" flag like already demonstrated well in the answers by Michel Keijzers, Bas in het Feld and EvilTeach.
  3. (C++ only) surround the code-section with a try-catch-block and throw and exception when you want to leave the code. But keep in mind that exceptions are usually supposed to be used for error-handling. So you should only use this pattern when terminating the loops is the result of an error conditions.
like image 20
Philipp Avatar answered Feb 13 '23 06:02

Philipp