I personally do not like the second, I would use:
for (int i = 0; i < n; ++i);
int i = 0 vs int i(0)
There is no difference whatsoever, they do not even compile with the same assembly instructions (without optimization):
int main() { int i = 0;
int i = 0 version:
main: pushq %rbp movq %rsp, %rbp movl $0, -4(%rbp) movl $0, %eax popq %rbp ret
int i(0) version:
main: pushq %rbp movq %rsp, %rbp movl $0, -4(%rbp) movl $0, %eax popq %rbp ret
i < n vs i != n
You are correct that != May introduce some interesting errors:
for (int i = 0; i != 3; ++i) { if (i == 2) i += 2;
The comparison != mainly used for iterators that do not define the < (or > ) operator. Perhaps this is what the author had in mind?
But here the second version is clearly better, since it more clearly states its intention than the other (and introduces fewer errors).
i++ vs ++i
For built-in types (and other trivial types), such as int , there is no difference as the compiler will optimize temporary return values. Here, again, some iterators are expensive, and therefore creating and destroying can be a performance hit.
But this really does not matter in this case, since even without optimization they produce the same combined output!
int main() { int i = 0; i++;
i++ version:
main: pushq %rbp movq %rsp, %rbp movl $0, -4(%rbp) addl $1, -4(%rbp) movl $0, %eax popq %rbp ret
++i version:
main: pushq %rbp movq %rsp, %rbp movl $0, -4(%rbp) addl $1, -4(%rbp) movl $0, %eax popq %rbp ret