mirror of
https://github.com/cpp-best-practices/cppbestpractices.git
synced 2025-12-17 19:24:36 +03:00
Merge pull request #24 from rob100/increment
Improvement for ++i vs i++
This commit is contained in:
@@ -270,12 +270,13 @@ for (int i = 0; i < 15; i++)
|
|||||||
std::cout << i << '\n';
|
std::cout << i << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Good Idea
|
// Good Idea
|
||||||
for (int i = 0; i < 15; ++i)
|
for (int i = 0; i < 15; ++i)
|
||||||
{
|
{
|
||||||
std::cout << i << '\n';
|
std::cout << i << '\n';
|
||||||
}
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
Even if many modern compilers will optimize this two loops to the same assembly code, it is still good practice to prefer `++i`. There is absolutely no reason not to and you can never be certain that your code will not pass a compiler that does not optimize this.
|
||||||
|
You should be also aware that the compiler will optimize this only for integer types and not for loops with iterators or objects with an overloaded ++operator.
|
||||||
|
The bottom line is that it is always easier and recommended to use the pre-increment operator if it is semantically identical to the post-increment operator.
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user