3 ms·
Decrementing loops is the one place where I have indulged in some trickery. I do: for (size_t i = 9; i --> 0; ) This has the advantage to be very easy to
by yoha 10y ago
Decrementing loops is the one place where I have indulged in some trickery. I do:
for (size_t i = 9; i --> 0; )
This has the advantage to be very easy to pattern-match once known. Obviously, for a beginner, I would just do:
for (int i = 9; i >= 0; i -= 1)
- colanderman 10y agoEveryone should write your second example. The first does nothing but confuse. C has enough hazing rituals without garbage like "-->". The fewer tricks and patterns you use in C, the higher chance actual bugs have of being caught. Cutesy tricks like "-->" confuse human analysis and gain nothing.
- yoha 10y agoThis is about weighing correction versus readability. In the "arrow operator" version, the readability is decreased; in the "proper" version, a type cast is required, and this can lead to bugs with values greater than 2^sizeof(ssize_t). Obviously, I just follow the convention when contributing to an existing project.
- pwdisswordfish 10y ago...values greater than 10?
- deleted 10y ago[deleted]
- cygx 10y agothis can lead to bugs with values greater than 2^sizeof(ssize_t) The range of indexable array elements is not only constrained by the unsigned type size_t, but also by the signed type ptrdiff_t, so you could always go with the latter instead of the non-ISO ssize_t.
- deleted 10y ago[deleted]
- timow1337 10y agonow do the second example with an unsigned type.
- yoha 10y agoThe point is that a beginner does not need to care about signedness. When you get to that point, you can take the time to explain how to loop properly over it.
- FloDo 10y agoDo you even realize that these two loops are not equivalent? One of them starts at 8, then other one starts at 9 ...
- yoha 10y agoRight, my bad. I tend to write loops in the former style, thinking of them as reversed(range(9)). This is another advantage of this style. I should have been more cautious when writing the second one.
- kLeeIsDead 10y agoThat first example reads like a horrible pun.