I need the opinion of stack overflow to settle something that has been sitting in the back of my head about for loop efficiency. Now, when I began programming, "getting it to work" was a big priority and most of my for loops looked like this.
for (int i = 0; i < N; i++) {;}
Then I was tought, especially with C++ development that pre-increment saves you some calls, and considering that would be N calls and it doesn't alter the readability I got into the habit of.
for (int i = 0; i < N; ++i) {;}
This was good enough for a while, but focusing on the readability, and after reading some of Code Complete by Steve McConnell, I arrived at this.
for (int loop_index = 0; loop_index < loop_count; ++loop_index) {;}
And these variables change based on the context of the code. Then I read some of Effective C++ about built in types constructors and assignment. And basically that the difference between
int i = 42;
and
int i(42);
Is that the former one calls the constructor and the assignment operator while the latter only the constructor. So I got that into my routine whilst coding. So my question, is this the most efficient and readable way of writing a for loop:
for (int loop_index(0); loop_index < loop_counter; ++loop_index) {;}
int, neither of these issues make any difference, and in practice copy-elision means that copy- vs. direct-initialisation is almost never a concern even for complicated types. Pre-increment is a good habit, since it can occasionally be more efficient, without affecting readibility. Long vs. short variable names are purely a matter of taste; personally, I findieasier to read thanloop_index, but others will disagree.