Hacker News new | ask | show | jobs
by stabbles 2539 days ago
In C++ you typically access arrays with unsigned integers (size_t), and a common pitfall is:

    for (size_t i = v.size() - 1; i >= 0; --i) {
      std::cout << i << ": " << v[i] << std::endl;
To fix the infinite loop you could write:

    for (size_t i = v.size(); i > 0; --i) {
      std::cout << i - 1 << ": " << v[i - 1] << std::endl;
Neither is great. Switching to signed integers might make your compiler throw warnings at you.

However, 1-based indexing does not work out well with modular arithmetic:

    # 1 based
    v[1 + (i - 1) % v.size()]

    # 0 based
    v[i % v.size()]
There's pros and cons with both schemes.
1 comments

Yes, and in both cases the language should provide tools so you don't have to deal directly with those edge cases. For example in Julia, for modular arithmetic with 1-based indexing there is mod1 [1], and for iterating in Julia you should use eachindex which will always work for both 0 or 1 indexed arrays.

[1] https://docs.julialang.org/en/v1/base/math/#Base.mod1

[2] https://docs.julialang.org/en/v1/base/arrays/index.html#Base...