Game with arguments

Inspired by this .

Suppose we have a non-empty std::vector<T> v; is there any difference between

 for (int i = v.size() - 1; i >= 0; i--) { ///Stuff. } 

and

 for (int i = v.size(); i--; ) { ///Stuff. } 

?

I mean, I would not do this for the sake of readability, but who knows what can be useful in life ...

( Here is just a test to see that they are equivalent)

Edit: A point has i as an index for accessing the inverse vector (in case the index was preferable to having iterators)

Edit 2: Out of curiosity: they have a slightly different build code. See this and this .

+7
c ++
source share
2 answers

You might think of a for loop

 for (<decl-init> ; <condition> ; <post-adjust>) <body> 

as the gross equivalent of this while :

 <decl-init>; while (condition) { <body>; <post-adjust>; } 

The biggest difference between for and the above is the scope of the variables declared in the <decl-init> block, but this is not important for the analysis below.

Rewriting both loops as a while gives you the following:

 int i = v.size() - 1; while ( i >= 0 ) { <body>; i--; } 

against.

 int i = v.size(); while (i--) { <body>; } 

As you can see, the only difference is that i decreases before the iteration is entered, and the condition starts with i more by 1 than in the first cycle. These two settings β€œcancel each other out”, making your loops technically equivalent. Aesthetics is a completely different matter: conditions with side effects are more difficult to understand than β€œpure” ones, so the first cycle is more readable.

+4
source share

This is a legal way to do this, but using i-- as a condition in a for loop is a terrible idea in terms of readability.

The for loop is designed to consist of three parts - why do people get stronger?

People who read your code will be happy if you follow the traditional for loop:

 for (int i = v.size() - 1; i >= 0; i--) { ///Stuff. } 
+2
source share

All Articles