4 ms·
Clever! Use of `i--` in loop for condition check wasn't intuitive at first. Apparently `i--` will return the current value of i (before decrementing).
by pyvek 13y ago
Clever!
Use of `i--` in loop for condition check wasn't intuitive at first. Apparently `i--` will return the current value of i (before decrementing).
- waterlion 13y agoNot intuitive? What do you think a post-decrement does do if not that?
- maaaats 13y agoThe clever part here is that it's defined as: for(i=4;i--;) instead of the more common (off by one?) for(i=4; i > 0; i--) syntax
- waterlion 13y agoThat is clever.
- xmonkee 13y agoI recommend reading K&R (http://en.wikipedia.org/wiki/The_C_Programming_Language http://en.wikipedia.org/wiki/The_C_Programming_Language) if you haven't already. It's got all sorts of elegant tricks like this. But of course it depends on very particular implementation details at times.
- waterlion 13y agoDon't worry, I have (hence my disbelief at the first comment). Funny we've come full circle (via e.g. Java) back to the point where that is valid code.
- dspillett 13y agoA lot of people forget (or never knew) that the increment and decrement operators return a value as well as affecting the target variable, and that you can put what-ever you like in the iteration end control portion of a for statement as long as it returns truey/falsey.
- tehwebguy 13y agoi-- returns the value before, --i returns the value after decrementing
- delinka 13y agoThere's pre-increment (++i), post-increment (i++), pre-decrement (--i), post-decrement (i--). The pre-ops operate on the variable and resolve to the new value. The post-ops resolve to the current value, and then operate on the variable.