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.
  • 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
                      • 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

                        G Offline
                        G Offline
                        Gary Huck
                        wrote on last edited by
                        #68

                        Opinion: goofy. There's no reason you can't have a while (!done) construct. Better yet, esp for the next guy, put in something meaningful. Yeah, for kicks one can do a loop-infinitely construct but you'd better comment why.

                        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
                          Mark AJA
                          wrote on last edited by
                          #69

                          Sometimes if I want to tempory remove some code I use; IF false THEN Code to tempory remove. ENDIF

                          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
                            Mikel Taylor
                            wrote on last edited by
                            #70

                            I hate to sound like a politician, but it depends. However, when there is a clear way to use "either," I personally prefer "for" looping. If working with object arrays, data rows, etc, I prefer to either check the count in an "if" block (or the UBOUND in the case of an array >-1) prior to the for loop. This approach allows you to predetermine iterations (if any are needed) at runtime- with your max value value being a variable. I usually reserve the use of "while" loops for conditions that are not numeric in nature... i.e. Fuzzier routines. In these cases, I usually place a boolean variable AND a counter out of the scope of the procedure and wrap a MAX If on loop iterations. I usually only go down this road if I am having to enumerate using self-calling recursion or something complex like that.

                            I float like a butterfinger & stank like a bee.

                            1 Reply Last reply
                            0
                            • N Nish Nishant

                              Christopher Duncan wrote:

                              Hang the app with an endless loop?

                              Only on a single core machine :-D

                              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

                              P Offline
                              P Offline
                              Pcube
                              wrote on last edited by
                              #71

                              That's incorrect. This code will only hang a single core machine if there are no interrupts to force context switching (which is the case on the vast majority of machines that run an OS, anyway). Also, this code is useful to spawn a thread that continuously polls hardware. If you have a piece of hardware that can change its output at any given time, but you're not sure when, you can spawn the equivalent to a listener thread to capture (sample) changes at the output. In fact, this code is useful in many "thread listener" type scenarios, such as when a server is idling and listening for clients...

                              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
                                skunkmeister
                                wrote on last edited by
                                #72

                                DirectX programming relies on while(true) for the primary loop. As long as a graceful exit exists (catching exceptions is not graceful), this is a valid programming code piece.

                                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
                                  Macotti
                                  wrote on last edited by
                                  #73

                                  I never got to use it in production but i used it once in my undergraduate thesis. I was working with artificial neural networks simulations and I couldn't find any way on how to determine how long it will take a particular ANN to learn. So I kept the loop going until the error was lower than that of the maximum allowed. I had no choice, the iteration can go from a few thousands to millions.

                                  1 Reply Last reply
                                  0
                                  • A Alan Balkany

                                    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 Offline
                                    R Offline
                                    RineezTVM
                                    wrote on last edited by
                                    #74

                                    I have used while(true) but only in some kind of Listener threads.

                                    1 Reply Last reply
                                    0
                                    • A Alan Balkany

                                      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.

                                      P Offline
                                      P Offline
                                      PICguy
                                      wrote on last edited by
                                      #75

                                      Good thoughts: pacemaker or long running app where shutting down the computer is how to exit. But what about running under a multitasking OS like this: while(true)

                                      {
                                      osWaitMilliseconds(x);
                                      doStuff();
                                      }

                                      No need to spawn a task every x milliseconds when one is waiting to be resumed. Or how about PIC code that looks like this:

                                      mainLoop:
                                      call sub1
                                      call sub2
                                      ...
                                      call subN
                                      goto mainLoop

                                      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
                                        Asday
                                        wrote on last edited by
                                        #76

                                        Call it bad practice but I'm a hobbyist, and I use that sorta stuff in my Python all the time, things like displaying a menu, giving the user a choice, and breaking (the function, not the trainwreck), when the user's asking to quit.

                                        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