Tech Off Thread

8 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Coding convention (C++)

Back to Forum: Tech Off
  • User profile image
    cro

    Which of the following would you use, and why :

    1.
    bool found = false;
    unsigned int index = 0;
    while (index < count && !found)
    {
       if (a[index] == b)
       {
          // do something
          found = true;
       }
       index++;
    }

    2.
    for (unsigned int index = 0; index < count; ++index)
    {
       if (a[index] == b)
       {
          // do something
          break;
       }
    }

    I use most often the number 2, but since I read some convention that used number 1, I would like to know what do you use.

    Thanks.

  • User profile image
    JohnAskew

    I prefer determinant looping whenever possible to protect against infinite looping.

    for > while

  • User profile image
    cokert

    From an readability point, number 1 would be considered better. 

    What you're doing is looping until you find what you're looking for, or you hit a limit on times looped.  That's all stated right from the start with option 1.  For option 2, the statement is in there, but you have to dig a little deeper/think a little harder to find what the intent is.

    While it can be argued that there shouldn't be much thought required to determine the point of the loop in either case, unless you're writing throw away code to test a concept, you should always be thinking about they person that will be coming in later.  The more obvious you can express your intent with your code, the easier it will always be to maintain.

  • User profile image
    AndyC

    I don't like break being used to end loops prematurely, it makes it less obvious what the pre and post conditions of the loop are.

  • User profile image
    Matthew van Eerde

    how about

    unsigned index = 0;
    bool bFound = find(b, a, count, &index);

  • User profile image
    Massif

    I'd prefer number 2, just as it's more concise.

    But then, I usually seem to want to know the equivalent of your "found" variable later on anyway.

  • User profile image
    Massif

    cro wrote:
    Witch of the following would you use, and why :


    Also can't resisit pointing that out, given that today is all hallow's eve.

  • User profile image
    cro

    I would like to say that it was intended, but no Big Smile

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.