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