Thread: are flags poor practice in a while loop?

  1. #1
    Registered User dinjas's Avatar
    Join Date
    Feb 2005
    Location
    Vancouver, Washington
    Posts
    40

    are flags poor practice in a while loop?

    Hi, I'm learning C and have been stumbling my way about. Anyhow, I've been wondering if it is poor practice to control a while loop with a flag. I've found it convenient at times. I assume it is probably better to use the condition that causes the flag to change but sometimes I have more than one thing that should cause me to get out of the loop. Also, setting the flags value based on the condition that caused the flag to be set seems like it can come in handy after the loop. Here's a code snippet of an example (sorry if it's not the greatest..)

    Code:
    while(!flag)
      {
         smaller=i;
         if(left <= n && array[left] < array[i])
          smaller=left;
         if(right <= n && array[right] < array[smaller])
          smaller=right;
    
         if(smaller != i)
         {
           tmp=array[i];
           array[i]=array[smaller];
           array[smaller]=tmp;
           i=smaller;
           left=2*i;
           right=2*i+1;
         }
         else
           flag=1;
    
         if(left > n)
           flag=2;
      }
    Is that ok? I'm trying to avoid developing bad habits and often the feedback I get from instructors is a bit lacking. Thanks!

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    It is usually better to just use the condition that causes the loop to be set, as you said, but also as you said, if you have multiple conditions that can cause the flag to be set, your method might be cleaner. I would agree, but you also might want to take a look at the continue and/or break statements (I can't remember which one is used for breaking out of loops - but one of those might help to answer your question).

  3. #3
    ---
    Join Date
    May 2004
    Posts
    1,379
    break will break out of a loop, continue will skip to the next iteration.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loop within loop won't work
    By Ayreon in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 10:44 AM
  2. nested loop, simple but i'm missing it
    By big_brother in forum C Programming
    Replies: 19
    Last Post: 10-23-2006, 10:21 PM
  3. While loop misbehaving (or misunderstanding)
    By mattAU in forum C Programming
    Replies: 2
    Last Post: 08-28-2006, 02:14 AM
  4. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  5. loop issues
    By kristy in forum C Programming
    Replies: 3
    Last Post: 03-05-2005, 09:14 AM