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) {;}
Actually,
is fine.
iis anint, so the compiler will optimise the post-increment away anyway. Whether you initialise anintwithint i(42);or withint i = 42;is also a question of taste.I would also call the iterator
i, instead ofloop_index. The former is ubiquitously understood, while the latter is strange.If you are dealing with iterators, however, the picture changes. Chances are
it++will still be optimised to++it, but here, I’d rather use pre-increment.