Using "break" to Break Out of Multiple Loops in One Call

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • O.B.

    Using "break" to Break Out of Multiple Loops in One Call

    Does C# support anything like PHP's break command that optionally
    accepts a parameter specifying how many loops to break out of?
  • =?Utf-8?B?RGF2aWQgQW50b24=?=

    #2
    RE: Using "break&quo t; to Break Out of Multiple Loops in One Call

    No - 'break' and 'continue' always apply to the innermost loop.
    You will need to set and test flags to do what you want (or - gasp - goto).
    --
    Source code converters: Convert between C#, C++, Java, VB, and Python with the most accurate and reliable source code converters

    C++ to C#
    C++ to VB
    C++ to Java
    Instant C#: VB to C#
    Instant VB: C# to VB
    Instant C++: VB or C# to C++/CLI
    Java to VB & C# Converter: Java to VB or C#


    "O.B." wrote:
    Does C# support anything like PHP's break command that optionally
    accepts a parameter specifying how many loops to break out of?
    >

    Comment

    • christery@gmail.com

      #3
      Re: Using "break&quo t; to Break Out of Multiple Loops in One Call

      On 15 Feb, 18:31, "O.B." <funkj...@bells outh.netwrote:
      Does C# support anything like PHP's break command that optionally
      accepts a parameter specifying how many loops to break out of?
      Not that Im aware of, and there would be grunts in the cleraing of
      code if I found one...

      for(;;int i(for(i=0;i<100 ;for(;console.w riteline("{0}\n ",i;for(;;i +
      +for(;;break(2) )))));
      have to try that... someday... it sholdnt work, but giving an example
      of why not.. it should stop at writing nothing but who knows...
      //CY

      Comment

      • Jeroen Mostert

        #4
        Re: Using &quot;break&quo t; to Break Out of Multiple Loops in One Call

        O.B. wrote:
        Does C# support anything like PHP's break command that optionally
        accepts a parameter specifying how many loops to break out of?
        No. And that's not very nice to begin with (requiring the programmer to
        count carefully). Labeled breaks a la Java would be better, but it doesn't
        have that either.

        If you really think it makes the code easier to read, you can always use
        goto. If the "multi-level break" is to handle a rare error condition, you
        could throw an exception instead. If that's the case, though, you should
        probably split things up in multiple functions. That would also allow you to
        use "return" to break out of all loops in the current function.

        --
        J.

        Comment

        • Donkey Hot

          #5
          Re: Using &quot;break&quo t; to Break Out of Multiple Loops in One Call

          "Peter Duniho" <NpOeStPeAdM@nn owslpianmk.comw rote in
          news:op.t6ld6ps z8jd0ej@petes-computer.local:
          Either way, I don't think there's anything inherently bad about
          labeled "break" statements or "goto" statements. Sometimes they are
          just what you need. Just remember not to aim at your foot when using
          them. :)
          >
          There's nothing bad in goto. I just love the longjmp() !!

          Comment

          • Peter Duniho

            #6
            Re: Using &quot;break&quo t; to Break Out of Multiple Loops in One Call

            On Fri, 15 Feb 2008 17:26:49 -0800, Donkey Hot <spam@plc.is-a-geek.com>
            wrote:
            There's nothing bad in goto. I just love the longjmp() !!
            Well, sure. But these days we have exceptions to provide for that.

            In fact, I'd say if anything, the descendant of longjmp() is much more
            broadly accepted than that of goto. :)

            Comment

            • Scott Roberts

              #7
              Re: Using &quot;break&quo t; to Break Out of Multiple Loops in One Call


              "Peter Duniho" <NpOeStPeAdM@nn owslpianmk.comw rote in message
              news:op.t6ld6ps z8jd0ej@petes-computer.local. ..
              Personally, I'm not of the mind that "goto" statements are inherently
              bad. They certainly can be misused, and may well be misused much more
              than other language constructs. But they also have their place (and I
              don't just mean as a replacement for falling through in "case" statements
              :) ).
              Would you mind providing one such example?

              Comment

              • Peter Duniho

                #8
                Re: Using &quot;break&quo t; to Break Out of Multiple Loops in One Call

                On Sat, 16 Feb 2008 08:16:53 -0800, Scott Roberts
                <sroberts@no.sp am.here-webworks-software.comwro te:
                >
                "Peter Duniho" <NpOeStPeAdM@nn owslpianmk.comw rote in message
                news:op.t6ld6ps z8jd0ej@petes-computer.local. ..
                >Personally, I'm not of the mind that "goto" statements are inherently
                >bad. They certainly can be misused, and may well be misused much more
                >than other language constructs. But they also have their place (and I
                >don't just mean as a replacement for falling through in "case"
                >statements :) ).
                >
                Would you mind providing one such example?
                Well, one common scenario is error-handling. In some cases, it makes
                sense to have a single exit point in a method so that things can be
                cleaned up in a single block of code rather than repeating that code, or
                some subset, throughout the method. Using a "goto" statement allows you
                to place that cleanup in a single place (I generally put it at the end of
                the method), jumping to it on an error, and otherwise falling straight
                through.

                Nesting a bunch of "if()" statements can accomplish the same thing, but it
                can create a difficult-to-read pattern of indentation. Using a "goto"
                provides a lot of the same readability benefits that using exceptions for
                failures can as well.

                Are there other ways to do that? Sure, especially in C# (which has
                "using" as well as exceptions). But those alternatives don't always
                result in code that's as readable. And does the presence of those
                alternatives mean that a "goto" statement is bad? No, not at all. Only
                someone who had a blanket objection to using a "goto" statement for the
                sake of the objection would say it was.

                The fact is, even if you never write a "goto" statement, you use "goto"s
                all the time. As long as you're keeping the code structured as you use a
                "goto" statement, you haven't done anything the compiler wouldn't do
                anyway. And if the use of the "goto" makes the code more readable, then
                that's an advantage over shoe-horning your code into whatever alternative
                the language would require to accomplish the same thing.

                Pete

                Comment

                • Dilip

                  #9
                  Re: Using &quot;break&quo t; to Break Out of Multiple Loops in One Call

                  On Feb 16, 3:11 pm, "Scott Roberts" <srobe...@no.sp am.here-webworks-
                  software.comwro te:
                  "Peter Duniho" <NpOeStPe...@nn owslpianmk.comw rote in message
                  >
                  news:op.t6mq92h e8jd0ej@petes-computer.local. ..
                  >
                  >
                  >
                  On Sat, 16 Feb 2008 08:16:53 -0800, Scott Roberts
                  <srobe...@no.sp am.here-webworks-software.comwro te:
                  >
                  "Peter Duniho" <NpOeStPe...@nn owslpianmk.comw rote in message
                  >news:op.t6ld6p sz8jd0ej@petes-computer.local. ..
                  >Personally, I'm not of the mind that "goto" statements are inherently
                  >bad. They certainly can be misused, and may well be misused much more
                  >than other language constructs. But they also have their place (and I
                  >don't just mean as a replacement for falling through in "case"
                  >statements :) ).
                  >
                  Would you mind providing one such example?
                  >
                  I am not Peter Duniho but I can provide you an example from a real
                  world high-performance middle-ware product. I lifted this piece out
                  of the codebase of this product (http://www.zeroc.com)

                  Consider this snippet that listens on a socket:

                  public static void doListen(Socket socket, int backlog)
                  {
                  repeatListen:

                  try
                  {
                  socket.Listen(b acklog);
                  }
                  catch(SocketExc eption ex)
                  {
                  if(interrupted( ex))
                  {
                  goto repeatListen;
                  }

                  closeSocketNoTh row(socket);
                  throw new Ice.SocketExcep tion(ex);
                  }
                  }

                  public static bool interrupted(Win 32Exception ex)
                  {
                  return ex.NativeErrorC ode == WSAEINTR;
                  }

                  There are probably other ways to do this without using goto but you
                  will only end up obfuscating the intent of the code for some mythical
                  purity.

                  Comment

                  • Scott Roberts

                    #10
                    Re: Using &quot;break&quo t; to Break Out of Multiple Loops in One Call


                    "Dilip" <rdilipk@lycos. comwrote in message
                    news:007a31b5-9dea-489b-9822-6c9532fd74ea@p2 5g2000hsf.googl egroups.com...
                    On Feb 16, 3:11 pm, "Scott Roberts" <srobe...@no.sp am.here-webworks-
                    software.comwro te:
                    >"Peter Duniho" <NpOeStPe...@nn owslpianmk.comw rote in message
                    >>
                    >news:op.t6mq92 he8jd0ej@petes-computer.local. ..
                    >>
                    >>
                    >>
                    On Sat, 16 Feb 2008 08:16:53 -0800, Scott Roberts
                    <srobe...@no.sp am.here-webworks-software.comwro te:
                    >>
                    >"Peter Duniho" <NpOeStPe...@nn owslpianmk.comw rote in message
                    >>news:op.t6ld6 psz8jd0ej@petes-computer.local. ..
                    >>Personally, I'm not of the mind that "goto" statements are inherently
                    >>bad. They certainly can be misused, and may well be misused much
                    >>more
                    >>than other language constructs. But they also have their place (and
                    >>I
                    >>don't just mean as a replacement for falling through in "case"
                    >>statements :) ).
                    >>
                    >Would you mind providing one such example?
                    >>
                    >
                    I am not Peter Duniho but I can provide you an example from a real
                    world high-performance middle-ware product. I lifted this piece out
                    of the codebase of this product (http://www.zeroc.com)
                    >
                    Consider this snippet that listens on a socket:
                    >
                    public static void doListen(Socket socket, int backlog)
                    {
                    repeatListen:
                    >
                    try
                    {
                    socket.Listen(b acklog);
                    }
                    catch(SocketExc eption ex)
                    {
                    if(interrupted( ex))
                    {
                    goto repeatListen;
                    }
                    >
                    closeSocketNoTh row(socket);
                    throw new Ice.SocketExcep tion(ex);
                    }
                    }
                    >
                    public static bool interrupted(Win 32Exception ex)
                    {
                    return ex.NativeErrorC ode == WSAEINTR;
                    }
                    >
                    There are probably other ways to do this without using goto but you
                    will only end up obfuscating the intent of the code for some mythical
                    purity.
                    >
                    Hmmm, here's my attempt, but you may be right. I'll admit that the original
                    is pretty good. Thanks for the example.

                    // The intent here should be pretty clear: keep calling
                    // "tryListen" until it returns "true". Although, it's not
                    // entirely clear *why* tryListen might return false.
                    public static void doListen(Socket socket, int backlog)
                    {
                    while (!tryListen(soc ket, backlog)) ;

                    // or

                    bool success = tryListen(socke t, backlog);
                    while (!success)
                    success = tryListen(socke t, backlog);
                    }

                    // The intent here may be a little obfuscated. It's not clear
                    // at all that you are going to retry if "interrupte d".
                    public static bool tryListen(Socke t socket, int backlog)
                    {
                    try
                    {
                    socket.Listen(b acklog);
                    }
                    catch(SocketExc eption ex)
                    {
                    if(interrupted( ex))
                    {
                    // Listen failed, try again.
                    return false;
                    }

                    closeSocketNoTh row(socket);
                    throw new Ice.SocketExcep tion(ex);
                    }

                    // Listen succeeded.
                    return true;
                    }

                    public static bool interrupted(Win 32Exception ex)
                    {
                    return ex.NativeErrorC ode == WSAEINTR;
                    }

                    Comment

                    • Steve Gerrard

                      #11
                      Re: Using &quot;break&quo t; to Break Out of Multiple Loops in One Call

                      Dilip wrote:
                      >
                      I am not Peter Duniho but I can provide you an example from a real
                      world high-performance middle-ware product. I lifted this piece out
                      of the codebase of this product (http://www.zeroc.com)
                      >
                      Consider this snippet that listens on a socket:
                      >
                      public static void doListen(Socket socket, int backlog)
                      {
                      repeatListen:
                      >
                      try
                      {
                      socket.Listen(b acklog);
                      }
                      catch(SocketExc eption ex)
                      {
                      if(interrupted( ex))
                      {
                      goto repeatListen;
                      }
                      >
                      closeSocketNoTh row(socket);
                      throw new Ice.SocketExcep tion(ex);
                      }
                      }
                      >
                      public static bool interrupted(Win 32Exception ex)
                      {
                      return ex.NativeErrorC ode == WSAEINTR;
                      }
                      >
                      Hmm, I didn't know you could jump out of a try block with a goto, then re-enter
                      the block, very interesting...

                      How about:

                      public static void doListen(Socket socket, int backlog)
                      {
                      bool retry = true;
                      while (retry)
                      {
                      try
                      {
                      socket.Listen(b acklog);
                      retry = false;
                      }
                      catch(SocketExc eption ex)
                      {
                      if (!interrupted(e x))
                      {
                      closeSocketNoTh row(socket);
                      throw new Ice.SocketExcep tion(ex);
                      }
                      }
                      }
                      }



                      Comment

                      • Oren Elrad

                        #12
                        Re: Using &quot;break&quo t; to Break Out of Multiple Loops in One Call

                        Another situation is where a particular operation will invalidate the
                        data being processes. For instance


                        start:
                        Generate dataset

                        for( - data set - )
                        while (something something)
                        for( - dataset - )
                        if (something something)
                        {
                        something that invalidates dataset
                        goto start:
                        }

                        *** Sent via Developersdex http://www.developersdex.com ***

                        Comment

                        Working...