1

I recently wrote an implementation for a simple linked list, and at several points in my code it looks like

Node* current_node = head;
while (current_node != nullptr) {
    if (current_node->data == query) {
    // perform some action
    break;
    }
current_node = current_node->next;
}

And I just recently thought I could re-implement this as

for (Node* current_node = head; current_node != nullptr; current_node = current_node->next) {
    if (current_node->data == query) {
    // perform some action
    break;
    }
}

I know that both are syntactically correct, and that any performance differences should be negligible, but I was wondering if having an equality condition in the check is generally implemented in a for-loop? Previously I have only used inequalities (ex: >, <, etc.) in for-loops. Which version is more conventional/readable?

Aposhian
  • 801
  • 1
  • 10
  • 27
  • Both have equality checks, what's the difference w.r.t the title of your question? Equality checks are totally fine, and using a for loop rather than the equivalent while-loop is probably easier for most people to read. There is no performance difference. Do what you find easiest to read and is correct. – GManNickG Feb 03 '16 at 22:09
  • 2
    `current_node->data != query` can be altogether in the loop condition. Just `&&` it. Then you just use `current_node` after the loop. – LogicStuff Feb 03 '16 at 22:10
  • @LogicStuff Would it matter that `current_node->data` would result in an invalid read if `current_node == nullptr` or would that be covered by the ordering of the `&&` operator? – Aposhian Feb 03 '16 at 22:24
  • 1
    Yes, see [this](http://stackoverflow.com/questions/5211961/how-does-c-handle-short-circuit-evaluation). – LogicStuff Feb 03 '16 at 22:25

1 Answers1

0

It's not a bad practice to loop through a linked list via for loop, but you can improve it to:

std::list<type> list;
auto it = std::find(begin(list), end(list), query);
if (it != end(list))
    // perform some action
Shoe
  • 74,840
  • 36
  • 166
  • 272