Thread: Our First Article - Searching Techniques By Prelude

  1. #16
    Software Developer jverkoey's Avatar
    Join Date
    Feb 2003
    Location
    New York
    Posts
    1,905
    I was personally wondering why in most of the example functions, there is the searching code which breaks out of the loop, and then after the loop, it gets tested as to whether it should return or not. Namely:

    Code:
      for ( i = 0; i < size; i++ ) {
        if ( key == list[i] )
          break;
      }
      if ( i < size ) {
        found = true;
        rec = &list[i];
      }
    That is the first example. Is there a benefit to writing the code this way? I would think it would be best to just return immediately from the loop, as then you don't have to do extra testing at the end.....correct me if I'm wrong here. It could very possibly be just for readability-sake.

  2. #17
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    There is no benefit to it, executionally speaking. In these examples it is primarily, as you suspect, for clarity and ease of understanding, particularly with respect to what operations are performed once the element is located (as a side note, it's funny that my boss requires that I write loops that way because he is uncomfortable with the idea of jumping out of the middle of a loop [as if the loop might continue executing], but we don't use C here either). Initially, there doesn't seem to be any overwhelming reason to write such simple code in this manner, but as an algorithm becomes more complex it's helpfulness becomes more apparent. I personally don't make a habit of writing loops this way and don't feel compelled to start now, but if one would desire such an edict, it wouldn't be unreasonable considering the benefit, especially with company code that multiple programmers will be trying to interpret.
    Last edited by LuckY; 01-31-2005 at 10:16 AM.

  3. #18
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Well, this particular method is actually probably a good one learning, as it emulates the operation of STL's iterators (checking for the 'end' iterator).
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  3. Visual C++ 2005 linking and file sizes
    By Rune Hunter in forum C++ Programming
    Replies: 2
    Last Post: 11-12-2005, 10:41 PM
  4. Article in GDM about DarkBasic PRO
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 09-03-2003, 06:27 PM