Hacker News new | past | comments | ask | show | jobs | submit login

> 'Modern' languages

After having many fencepost errors, I finally came to the conclusion that all my code shall henceforth be zero-based. I'm much happier not having those errors anymore. I.e.:

   for (i = 1; i <= N; ++i)
The <= is always a huge red flag for me, and I rewrite it as:

    for (i = 0; i < N; ++i)
and add a `1` in the body if I must.



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).


It'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.


You 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).


> 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.


In 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.


It's just better form. Also, if `i` is a struct with an overloaded postinc operator, it can be more expensive.


I 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.


Yeah, but why is it better form (I am coming from Java where it shouldn't make any difference)?


It'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.


I 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.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: