Jump to content

  • Log In with Google      Sign In   
  • Create Account


Breaking out of a double for loop


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
7 replies to this topic

#1 Rld_   Members   -  Reputation: 1384

Like
0Likes
Like

Posted 02 May 2012 - 11:40 AM

Hey guys,

I am busy with a small audio engine, playing .wav files and although everything works fine, I'm having some second thoughts about a certain part where I need to break out of 2 loops at certain points.

The way I do it now is as following:

static bool earlyout = false;
for(iterate through sounds)
{
   // gather some relevant data
   for(iterate through buffer)
   {
	  if(something)
	  {
		 earlyout = true;
		 break;
	  }
   }
   if(earlyout)
   {
	  earlyout = false;
	  break;
   }
}

it does the job, but I think this looks very ugly. The other option I had in mind was to use a goto: but I don't like using goto.. Does anyone have an idea of how I can do this in a more proper/cleaner way? If there is any at all?

Much appreciated!

Sponsor:

#2 SiCrane   Moderators   -  Reputation: 9574

Like
1Likes
Like

Posted 02 May 2012 - 11:48 AM

Some options: refactor the inner loop into its own function and break out based on the return value, refactor so that there's nothing after the two for loops and just return from the function, modify the iteration variable(s), work the early out condition into the iteration condition, etc. With a concrete example a better suggestion might be possible. Also, why are you making the condition variable static?

#3 alnite   Crossbones+   -  Reputation: 2087

Like
0Likes
Like

Posted 02 May 2012 - 12:22 PM

That's fine or do it like SiCrane said, or you can restructure your engine.

Why are you iterating through sounds? Are these sound effects? What if you put each one of sound effects to its own class, then have each one to be responsible of its own buffers?

#4 Rld_   Members   -  Reputation: 1384

Like
0Likes
Like

Posted 02 May 2012 - 12:51 PM

Thanks for the tips, I'm going over the code again to see if I can avoid the break altogether, I think it is possible, else the inner loop in a function seems to be a good option. I was using the static purely as I was testing some things out before I made some final adjustments and in here to simply make a point.

@alnite
I am iterating through the current active sounds as I need to mix them into a single buffer for playback. Basically I have an abstract sound class with some needed variables like 3D sound, looping, volume, etc. and specific sound classes (at the moment only .wav) which hold file format specifics. When I want to play a sound, I simply add it to a vector of currently active sounds that do their magic with the data and add it to the buffer (or in my case, 2) that I use for playback.

#5 Álvaro   Crossbones+   -  Reputation: 13010

Like
1Likes
Like

Posted 02 May 2012 - 01:12 PM

For the solutions involving refactoring things into functions, that's great as long as you can give the function a good name. If a chunk of code doesn't satisfy that rule, and especially if you have to pass a bunch of local variables to the helper function, I would much rather have a `goto' to break out of the nested loops.

`break' is just a `goto' to just past the loop. `continue' is just a `goto' to the end of the body of the loop. Since these usages of `goto' are common and perfectly acceptable, the language provides neat little aliases for them, and that way you don't need to write an ugly label. The language didn't provide a neat little alias from breaking out of nested loops (or a switch within a loop), so you need to write the ugly label. Give the label a good name and the code is perfectly readable.


for(iterate through sounds)
{
  // gather some relevant data
  for(iterate through buffer)
  {
    if(something)
	  goto BREAK_OUT_OF_LOOP_OVER_SOUNDS;
  }
}
BREAK_OUT_OF_LOOP_OVER_SOUNDS:;

Edited by alvaro, 02 May 2012 - 01:15 PM.


#6 clb   Members   -  Reputation: 1781

Like
1Likes
Like

Posted 02 May 2012 - 03:37 PM

When the outer loop is not of for-each style, you can do
for(int i = 0; i < n; ++i)
   for(int j = 0; j < m; ++j)
   {
      if (condition(i, j))
      {
         i = n; // Clear the condition of the outer loop so we don't make any extra iterations after finishing the inner loop.
         break; // Break inner loop.
      }
   }

If the conditions of the outer loop are complicated, you can transform that to similar thing you do using a boolean variable (but there's really no need to make it static):

bool iterating = true;
for(int i = 0; complicatedCondition(i) && iterating; ++i)
   for(int j = 0; j < m; ++j)
   {
      if (condition(i, j))
      {
         iterating = false; // Clear the condition of the outer loop so we don't make any extra iterations after finishing the inner loop.
         break; // Break inner loop.
      }
   }

But most often, as was mentioned above, I also favor turning the double loop into a single loop and a helper function which encloses the inner loop.
Me+PC=clb.demon.fi | C++ Math and Geometry library: MathGeoLib, test it live! | C++ Game Networking: kNet | 2D Bin Packing: RectangleBinPack | Use gcc/clang/emcc from VS: vs-tool | Resume+Portfolio | gfxapi, test it live!

#7 mhagain   Crossbones+   -  Reputation: 7866

Like
0Likes
Like

Posted 02 May 2012 - 03:48 PM

I'd personally favour either refactoring or goto. The alternate methods seem neat ways to avoid this, but the major advantage of refactor or goto is that it's immediately obvious to the reader (who may be yourself in 6 months time) what your intention is. goto is bad karma for sure, but only when using it instead of other more appropriate control-flow statements, and there are cases where using goto is actually cleaner, more legible, and less prone to unwanted side-effects than a tricksy method of avoiding it. With that said, I would say refactor first and only use goto if that's absolutely unacceptable.

Edited by mhagain, 02 May 2012 - 03:51 PM.

It appears that the gentleman thought C++ was extremely difficult and he was overjoyed that the machine was absorbing it; he understood that good C++ is difficult but the best C++ is well-nigh unintelligible.


#8 Servant of the Lord   Crossbones+   -  Reputation: 18735

Like
0Likes
Like

Posted 02 May 2012 - 04:31 PM

Most of the time I encounter such a situation, breaking the inner loop into its own function is the best solution, but occasionally (rarely) I find that gotos make more sense (though mine are usually the result of larger-scale architectural problems). If it's clean and easy to read using the goto do so, but first check about breaking the inner loop into a function - it definitely feels like (and usually is) the cleanest solution here.

In my entire code-base, I have two occurances of the word 'goto'. One I'm happy with, and one I'm not - but it needs re-factoring on a slightly larger architectural scale and I have more pressing areas of code to work on. The number of 'loops within a loop' broken into separate functions are probably around 20 or so, but I'm just guessing since I can't easily measure that. Number of 'loops within a loop' that don't need to be re-factored into separate functions (but also don't use goto) are probably about 10.
It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal

[Fly with me on Twitter] [Google+] [My broken website]

[Need web hosting? I personally like A Small Orange]





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS