How to avoid use of goto and break nested loops efficiently [on hold]

  • A+

I'd say that it's a fact that using goto is considered a bad practice when it comes to programming in C/C++.

However, given the following code

for (i = 0; i < N; ++i)  {     for (j = 0; j < N; j++)      {         for (k = 0; k < N; ++k)          {             ...             if (condition)                 goto out;             ...         }     } } out:     ... 

I wonder how to achieve the same behavior efficiently not using goto. What i mean is that we could do something like checking condition at the end of every loop, for example, but AFAIK goto will generate just one assembly instruction which will be a jmp. So this is the most efficient way of doing this I can think of.

Is there any other that is considered a good practice? Am I wrong when I say it is considered a bad practice to use goto? If I am, would this be one of those cases where it's good to use it?

Thank you

The (imo) best non-goto version would look something like this:

void calculateStuff() {     // Please use better names than this.     doSomeStuff();     doLoopyStuff();     doMoreStuff(); }  void doLoopyStuff() {     for (i = 0; i < N; ++i)      {         for (j = 0; j < N; j++)          {             for (k = 0; k < N; ++k)              {                 /* do something */                  if (/*condition*/)                     return; // Intuitive control flow without goto                  /* do something */             }         }     } } 

Splitting this up is also probably a good idea because it helps you keep your functions short, your code readable (if you name the functions better than I did) and dependencies low.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: