4 ms·
Any specific reason to use ++i over i++? I always use the latter but only out of habit. I've rarely seen code with the former (your idiom).
by chopin 7y ago
Any specific reason to use ++i over i++? I always use the latter but only out of habit. I've rarely seen code with the former (your idiom).
- lmm 7y agoIn theory extremely naive compilers may copy `i` if you use `i++` (since `i++` evaluates to the old value, whereas ++i can always be a destructive update), so some programmers have a habit of defaulting to ++i.
- WalterBright 7y agoIt's just better form. Also, if `i` is a struct with an overloaded postinc operator, it can be more expensive.
- jstimpfle 7y agoI think that is arguable. The form "array[idx++] = foo;" has undeniable elegance, and I still use it sometimes, even though I've developped a pretty verbose coding style in general.
- chopin 7y agoYeah, but why is it better form (I am coming from Java where it shouldn't make any difference)?
- WalterBright 7y agoIt's better form to not ask for a characteristic that you don't need. For example: 1. increment x 2. take the value of x, then increment x (1) is better form if you don't need the value of x.
- chopin 7y agoI just checked in Java, it is: 1. increment x, then take the value of x 2. take the value of x, then increment x Both are expressions in Java returning a value. My C is very rusty but I remember it being the same in C.
- tsimionescu 7y agoIt's usually a C++-ism, since in C++ generic iterators overwrite operator++, and when writing generic code, you must allow for this, since ++i is equivalent to i.operator++(), while i++ is equivalent to `auto x=i; i.operator++(); return x`. Given the author, I assume that this is also common in D.
- jstimpfle 7y agoYou can override the postfix increment operator as well. The argument I've heard for why in C++ prefix is preferred is that compilers have a harder time optimizing out the temporary object cruft (especially older compilers).
- WalterBright 7y ago> You can override the postfix increment operator as well. You can, but if there are side effects in the object's implementation then it can be less efficient.