2
$\begingroup$

Is it when you need faster performance, to iterate over a container, or when you don't need an index variable?

From my understanding it should be when you need to iterate over a container.

Am I understanding this properly?

$\endgroup$

closed as unclear what you're asking by Evil, David Richerby, Juho, chi, Yuval Filmus May 30 '17 at 21:19

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    $\begingroup$ What do you mean by a "range-based for loop" and a "regular for loop"? What's the difference you have in mind? Can you give a definition, an example, some context? What makes you think one is better? Did you read something somewhere that said that? $\endgroup$ – D.W. May 30 '17 at 1:43
  • 2
    $\begingroup$ I think questions about coding style are offtopic here. $\endgroup$ – Raphael May 30 '17 at 20:24
0
$\begingroup$

In my experience, if you don't need an index variable and don't need to iterate over the objects in a particular order, then range-based for loops can be easier to understand, and less verbose. Outside of those conditions, it's usually a matter of taste. You're basically saying, "for each object in the container, do this," as opposed to saying, "for each index in the container, retrieve the object at the index, and for each object you've retrieved, do this."

$\endgroup$
0
$\begingroup$

I follow a simple rule: Use regular for loops only if you HAVE to. Use range based anytime you can as they make your code cleaner, more concise and less prone to error.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.