Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. while (true) and for (; ; ) [modified]

while (true) and for (; ; ) [modified]

Scheduled Pinned Locked Moved The Lounge
hostingcloudquestion
76 Posts 48 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T TheGreatAndPowerfulOz

    RugbyLeague wrote:

    IDisposable to classes in C#

    That's silly. It serves no purpose, except obfuscation and misrepresentation, if you don't implement the IDisposable!

    "If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy Adams "Let me get this straight. You know her. She knows you. But she wants to eat him. And everybody's okay with this?" - Timon

    R Offline
    R Offline
    RugbyLeague
    wrote on last edited by
    #48

    I implement it - it just doesn't do anything. I like how a "using" easily and obviously defines a scope for a class. using(var foo = new foo()) { foo.DoStuff(); } feels better than: var foo = new foo(); foo.DoStuff(); because in the latter foo is still in scope after use - the former more explicitly defines the useful lifetime of foo - I know there are other probably more correct ways of doing this. I just like the "using" notation. I don't always use it of course.

    1 Reply Last reply
    0
    • B bob16972

      They are both handy from time to time (expression parsing and times when you don't know how many iterations will be needed). I personally prefer while(TRUE) so as not confuse any VB programmer that comes across my code.

      H Offline
      H Offline
      hairy_hats
      wrote on last edited by
      #49

      bob16972 wrote:

      I personally prefer while(TRUE) so as not confuse any VB programmer that comes across my code.

      :confused: Isn't that a reason to use for(;;) ?

      1 Reply Last reply
      0
      • W wizardzz

        What are your views on these? How often do you use or see them and in what cases? Just curious, it's a little debate with my project's Architect. To clarify, I don't mean the preference between the 2, but the use of such loops in production.

        "Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson

        modified on Thursday, March 10, 2011 12:10 PM

        A Offline
        A Offline
        alanevans
        wrote on last edited by
        #50

        I'd prefer someone do this:

        while(true)
        {
        if(matched condition A)
        {
        do something A
        break;
        }

        if(matched condition B)
        {
        do something B
        break;
        }

        }

        to this:

        bool exit = false;
        while(!exit)
        {
        if(matched condition A)
        {
        do something A
        exit = true;
        continue;
        }

        if(matched condition B)
        {
        do something B
        exit = true;
        continue;
        }
        }

        It's messy, longer and more prone to bugs when being supported/extended, and all just to avoid the "infinite loop", even though really it's just as "infinite".

        1 Reply Last reply
        0
        • W wizardzz

          What are your views on these? How often do you use or see them and in what cases? Just curious, it's a little debate with my project's Architect. To clarify, I don't mean the preference between the 2, but the use of such loops in production.

          "Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson

          modified on Thursday, March 10, 2011 12:10 PM

          S Offline
          S Offline
          Stefan_Lang
          wrote on last edited by
          #51

          I never do that. Every loop has legitimate conditions that should cause it to stop, be it timeout, an external command to stop (assuming the loop handles such commands), reaching the end of data, reaching the max number the loop counter type can hold (if you are using a counter, don't risk overflow!), whatever. Such cases are not exceptions! So they need to be treated and inquired appropriately. A good way to deal with hard to define termination conditions is to introduce and maintain a state variable. It can be a bool, an enum type, or even a struct that can hold additional information, such as the reason(s) for the most recent state change(s). You can even make it a class that treats it's own reporting, special logging and debug behaviour. Even for debugging an testing I define at the very least a maximum count.

          1 Reply Last reply
          0
          • W wizardzz

            What are your views on these? How often do you use or see them and in what cases? Just curious, it's a little debate with my project's Architect. To clarify, I don't mean the preference between the 2, but the use of such loops in production.

            "Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson

            modified on Thursday, March 10, 2011 12:10 PM

            M Offline
            M Offline
            M Towler
            wrote on last edited by
            #52

            I use these when the structure of the code dictates it would be helpful to have the loop termination condition in the *middle* of the loop. Something like the following for(;;) { // do some stuff if( stuff is now done ) break; // more stuff } Otherwise the alternative is to replicate the "// do some stuff" code before the first loop iteration, which is avoidable duplication. The other way to achieve this is to put "// do some stuff" into a function, then use the comma operator in the loop condition to execute some code first. I tend to regard the comma operator as a very last resort though, most programmers don't even realise it exists let alone how to use it.

            1 Reply Last reply
            0
            • W wizardzz

              What are your views on these? How often do you use or see them and in what cases? Just curious, it's a little debate with my project's Architect. To clarify, I don't mean the preference between the 2, but the use of such loops in production.

              "Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson

              modified on Thursday, March 10, 2011 12:10 PM

              A Offline
              A Offline
              alanevans
              wrote on last edited by
              #53

              I sometimes do this in C:

              void method(void)
              {
              //initialization, e.g. mallocs
              do //think try
              {
              //some stuff

              if(early exit condition)
              {
              break; //continue is also fine
              }
              //other stuff (but skipped in event of early exit condition)

              } while(false); //think finally
              //finalization, e.g. frees
              }

              This effectivly gives me a try...finally in C. Which helps reduce ifs nesting.

              1 Reply Last reply
              0
              • C CPallini

                Not always. In C applications, for instance, you may know in the middle of the loop that you've to exit and while you may skip the following statements with an if and then use the condition, I prefer an immediate break.

                If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                [My articles]

                J Offline
                J Offline
                Jun Du
                wrote on last edited by
                #54

                While(!done) won't prevent you from exiting in the middle of the loop. You can break anywhere you like. The point is that I prefer to use a loop in a controlled manner.

                Best, Jun

                C 1 Reply Last reply
                0
                • W wizardzz

                  Ah, I'm going to modify my original post. I wasn't referring to the preference between the 2, but the use of infinite loops, especially if there is no breaks to exit the loop. I guess we have a crash-only design for some applications.

                  "Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson

                  A Offline
                  A Offline
                  Alan Balkany
                  wrote on last edited by
                  #55

                  It depends on what the application calls for. There are numerous situations where while(true) is appropriate. Three years ago I did an application where the spec explicitly said to not handle shutting down the application. It was a long-running application, and my guess was they would simply shut down the computer when done. What about a heart pacemaker? If it exited the loop, someone might die.

                  R P 2 Replies Last reply
                  0
                  • J Jun Du

                    While(!done) won't prevent you from exiting in the middle of the loop. You can break anywhere you like. The point is that I prefer to use a loop in a controlled manner.

                    Best, Jun

                    C Offline
                    C Offline
                    CPallini
                    wrote on last edited by
                    #56

                    Jun Du wrote:

                    While(!done) won't prevent you from exiting in the middle of the loop. You can break anywhere you like.

                    Well that would look (to me) redundant. It's just matter of personal taste, but I think if .. break in the middle of the loop is a 'controlled manner' too. :)

                    If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                    This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                    [My articles]

                    J 1 Reply Last reply
                    0
                    • N Nish Nishant

                      Okay, I can't think of why anyone'd have a while-true (or otherwise infinite) loop that does not have any normal exit conditions. Although you could break out via an exception it just does not seem very clean to me.

                      Regards, Nish


                      New article available: Resetting a View Model in WPF MVVM applications without code-behind in the view My technology blog: voidnish.wordpress.com

                      A Offline
                      A Offline
                      Andrew Glowacki
                      wrote on last edited by
                      #57

                      while(true) { lock(syncObject) { if (checkSomeCriticalCondition()) break; } doSomeOtherStuff(); }

                      N N 2 Replies Last reply
                      0
                      • A Andrew Glowacki

                        while(true) { lock(syncObject) { if (checkSomeCriticalCondition()) break; } doSomeOtherStuff(); }

                        N Offline
                        N Offline
                        Nish Nishant
                        wrote on last edited by
                        #58

                        Uhm, what's your point? :-) You do have a break there (which is an exit point)! So yours is not an exit-less infinite loop!

                        Regards, Nish


                        New article available: Resetting a View Model in WPF MVVM applications without code-behind in the view My technology blog: voidnish.wordpress.com

                        A 1 Reply Last reply
                        0
                        • N Nish Nishant

                          Uhm, what's your point? :-) You do have a break there (which is an exit point)! So yours is not an exit-less infinite loop!

                          Regards, Nish


                          New article available: Resetting a View Model in WPF MVVM applications without code-behind in the view My technology blog: voidnish.wordpress.com

                          A Offline
                          A Offline
                          Andrew Glowacki
                          wrote on last edited by
                          #59

                          I know, just giving a solid example so there's no doubt. ;P

                          N 1 Reply Last reply
                          0
                          • A Andrew Glowacki

                            I know, just giving a solid example so there's no doubt. ;P

                            N Offline
                            N Offline
                            Nish Nishant
                            wrote on last edited by
                            #60

                            Andrew Glow wrote:

                            I know, just giving a solid example so there's no doubt.

                            Thanks for the 1 vote.

                            Regards, Nish


                            New article available: Resetting a View Model in WPF MVVM applications without code-behind in the view My technology blog: voidnish.wordpress.com

                            1 Reply Last reply
                            0
                            • C CPallini

                              Jun Du wrote:

                              While(!done) won't prevent you from exiting in the middle of the loop. You can break anywhere you like.

                              Well that would look (to me) redundant. It's just matter of personal taste, but I think if .. break in the middle of the loop is a 'controlled manner' too. :)

                              If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                              This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                              [My articles]

                              J Offline
                              J Offline
                              Jun Du
                              wrote on last edited by
                              #61

                              Yes, they are both "controlled". There is a slight difference. "if...break" can exit anywhere within the loop, whereas while(!done) exits at the end of a loop.

                              Best, Jun

                              1 Reply Last reply
                              0
                              • W wizardzz

                                What are your views on these? How often do you use or see them and in what cases? Just curious, it's a little debate with my project's Architect. To clarify, I don't mean the preference between the 2, but the use of such loops in production.

                                "Life should not be a journey to the grave with the intention of arriving safely in a pretty and well preserved body, but rather to skid in broadside in a cloud of smoke, thoroughly used up, totally worn out, and loudly proclaiming "Wow! What a Ride!" — Hunter S. Thompson

                                modified on Thursday, March 10, 2011 12:10 PM

                                F Offline
                                F Offline
                                Fabio Franco
                                wrote on last edited by
                                #62

                                I have used this only once in production. It's a windows service application that listen to connection requests on a background thread. Something like this:

                                while(true)
                                {
                                m_Socket = m_Listener.AcceptSocket(); // This is a blocking line which waits until a connection request arrives from the clinet.

                                //Do stuff from the connection request, then start over to keep listening for new requests
                                

                                }

                                Of course this code is part of a method that is enclosed on a try catch block that expects a ThreadAbortedException. Which is the way out of the loop. And that only happens when the user explicitly asks to do so or the service is stopped. I think the while(true) can be used, but with lot of care. And I think that there are very few scenarios where the danger of it's use is smaller than the need. So, if you can avoid it, avoid it. If not, make sure you know what you're doing and try to cover as many possibilities of things going wrong as possible.

                                1 Reply Last reply
                                0
                                • C CPallini

                                  Not always. In C applications, for instance, you may know in the middle of the loop that you've to exit and while you may skip the following statements with an if and then use the condition, I prefer an immediate break.

                                  If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
                                  This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
                                  [My articles]

                                  J Offline
                                  J Offline
                                  jsc42
                                  wrote on last edited by
                                  #63

                                  CPallini wrote:

                                  you may know in the middle of the loop that you've to exit and while you may skip the following statements with an if and then use the condition, I prefer an immediate break.

                                  What you have described is known as an n-and-a-half times loop. The Pascal P-Code compiler uses the following ungainly way of doing it (excuse the non-PASCAL syntax ... my Pascal is extremely rusty, but the principle is clear)

                                  DO
                                  (* bits before the test *)
                                  test = exit condition;
                                  IF (NOT test)
                                  (* bits after the test condition *)
                                  UNTIL (test)

                                  It always struck me as bad - the compiler writers having to use an idiom to do something that their language did not support cleanly - surely, they should be able to adjust the language when they saw its inherent deficiencies. Languages that I was involved with in the late 1970s always 'magically' got extensions that supported n-and-a-half times loops. For example, my Rationalised FORTRAN (which included block structured constructs long before FORTRAN 77 became available) had:

                                  LOOP
                                  bits before the test
                                  EXITIF condition // You could have multiple EXITIF sections
                                  bits after the test
                                  ENDLOOP

                                  (minor later variant was an EXITIFNOT statement as an alternative to EXITIF) A WHILE loop then simply becomes

                                  LOOP
                                  EXITIFNOT condition
                                  body of the loop
                                  ENDLOOP

                                  An UNTIL loop then simply becomes

                                  LOOP
                                  body of the loop
                                  EXITIF condition
                                  ENDLOOP

                                  A normal FOR/NEXT or DO/CONTINUE loop becomes

                                  controlvar = startvalue
                                  LOOP
                                  EXITIF controlvar > endvalue
                                  body of the loop
                                  controlvar = controlvar + step
                                  ENDLOOP

                                  A 'must do at least once' FOR/NEXT or DO/CONTINUE loop becomes

                                  controlvar = startvalue
                                  LOOP
                                  body of the loop
                                  controlvar = controlvar + step
                                  EXITIF controlvar > endvalue
                                  ENDLOOP

                                  Example: To see if an item is in an array

                                  i = 1 // Lower bound of subscript
                                  LOOP
                                  EXITIF i > noofelementsinthearray
                                  EXITIF array(i) = valuetofind // Previous EXITIF ensure that array subscript overflow will not occur
                                  i = i + 1
                                  ENDLOOP

                                  or

                                  i = 1 // Lower bound of subscript
                                  LOOP
                                  EXITIF i > noofelementsinthearray
                                  IF (array(i) = valuetofind)
                                  do whatever you want with the found value
                                  EXITIF true // I never got around to creating a simple unconditional EXIT statement!
                                  END IF
                                  i = i + 1
                                  ENDLOOP

                                  1 Reply Last reply
                                  0
                                  • A Andrew Glowacki

                                    while(true) { lock(syncObject) { if (checkSomeCriticalCondition()) break; } doSomeOtherStuff(); }

                                    N Offline
                                    N Offline
                                    ness2u2
                                    wrote on last edited by
                                    #64

                                    Andrew Glow wrote:

                                    while(true)
                                    {
                                    lock(syncObject)
                                    {
                                    if (checkSomeCriticalCondition())
                                    break;
                                    }

                                    doSomeOtherStuff();
                                    }

                                    If possible, I'd move the lock{ someCriticalCondition } out to a function returning boolean. Then toss the result of that as the while condition. while(CheckCondition()){ doSomeOtherStuff(); } The semantics are identical, unless there is code before the lock... In my opinion, this displays the intent of code/loop better than having an internal break.

                                    A 1 Reply Last reply
                                    0
                                    • N ness2u2

                                      Andrew Glow wrote:

                                      while(true)
                                      {
                                      lock(syncObject)
                                      {
                                      if (checkSomeCriticalCondition())
                                      break;
                                      }

                                      doSomeOtherStuff();
                                      }

                                      If possible, I'd move the lock{ someCriticalCondition } out to a function returning boolean. Then toss the result of that as the while condition. while(CheckCondition()){ doSomeOtherStuff(); } The semantics are identical, unless there is code before the lock... In my opinion, this displays the intent of code/loop better than having an internal break.

                                      A Offline
                                      A Offline
                                      Andrew Glowacki
                                      wrote on last edited by
                                      #65

                                      True. I guess having it just like this would be useless unless maybe doSomeOtherStuff actually used the same data in the critical section that other threads were using as well. In this case I would do something like this:

                                      while (true)
                                      {
                                      lock(syncObject)
                                      {
                                      if (checkSomeCriticalCondition())
                                      break;
                                      doSomeOtherStuff();
                                      }
                                      Sleep(someAmountOfTime);
                                      }

                                      ... I can see a lot more holes in this design now but I still think that having a critical section check could be used somehow.

                                      N 1 Reply Last reply
                                      0
                                      • A Andrew Glowacki

                                        True. I guess having it just like this would be useless unless maybe doSomeOtherStuff actually used the same data in the critical section that other threads were using as well. In this case I would do something like this:

                                        while (true)
                                        {
                                        lock(syncObject)
                                        {
                                        if (checkSomeCriticalCondition())
                                        break;
                                        doSomeOtherStuff();
                                        }
                                        Sleep(someAmountOfTime);
                                        }

                                        ... I can see a lot more holes in this design now but I still think that having a critical section check could be used somehow.

                                        N Offline
                                        N Offline
                                        ness2u2
                                        wrote on last edited by
                                        #66

                                        Depending on the language and framework's your using, there is probably a timer you could use to avoid the loop all together? If the bulk of the code in the loop is critical enough to require a lock, I wonder if it is something that would actually benefit from running in a multithreaded environment? I work mostly with C# and have seen very few scenarios where while(true) or for(;;) is the best choice. Just make sure its commented well!

                                        A 1 Reply Last reply
                                        0
                                        • N ness2u2

                                          Depending on the language and framework's your using, there is probably a timer you could use to avoid the loop all together? If the bulk of the code in the loop is critical enough to require a lock, I wonder if it is something that would actually benefit from running in a multithreaded environment? I work mostly with C# and have seen very few scenarios where while(true) or for(;;) is the best choice. Just make sure its commented well!

                                          A Offline
                                          A Offline
                                          Andrew Glowacki
                                          wrote on last edited by
                                          #67

                                          Very good point, for some reason I always assume people are using .NET. I did mean C# anyway. However, nothing comes to mind for a concrete example of where this would be useful at the moment.

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups