CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jul 2012
    Posts
    7

    [RESOLVED] using break statement in a while loop

    So basically I am using a background worker to do a bunch of stuff.

    I have a method that says something along the lines of:

    Code:
    while (!_backgroundWorker.CancellationPending)
    {
         // do a bunch of stuff here
    
         // end of doing a bunch of stuff
         break;
    }
    My question is this, is there a *BETTER* way to break from this statement when its done doing what it needs to do?

    I was told break statements are usually not a good idea to use in while loops. Which kind of got under my skin because the person who told me is fresh from college and has 0 software development experience in a workforce. I can understand that when not using a background worker, you just set some condition to true or false at the end of the while statement which imo is close to the same thing as a break statement.

    I don't really see any alternative when using the background worker however. If the background worker has not been cancelled, how else do you get out it?

    Thanks,
    Joel

  2. #2
    Join Date
    Feb 2008
    Posts
    108

    Re: using break statement in a while loop

    If you use the while statement as follows:

    bool finished = false;

    while ((!finished) && (!_backgroundWorker.CancellationPending))
    {
    //When the exit condition is met-
    finished = true;
    }
    Developing using:
    .NET3.5 / VS 2010

  3. #3
    Join Date
    Jul 2012
    Posts
    7

    Re: using break statement in a while loop

    What advantage, if any does that give my application vs. the break statement?

  4. #4
    Join Date
    Feb 2008
    Posts
    108

    Re: using break statement in a while loop

    Coding standards were developed because frequently someone else will have to maintain your code, and having the code work will not necessarily make it understandable and maintainable. Using "break" to exit a "while" loop may not make it as clear as setting a flag when a set of conditions are met. You may want to know why an exit was made from the loop.
    Developing using:
    .NET3.5 / VS 2010

  5. #5
    Join Date
    Jul 2012
    Posts
    7

    Re: using break statement in a while loop

    Understandable. Thanks for clearing that up Jim!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured