4 ms·
I like this slick way cycle thru a range of numbers: c = c < 4 ? c + 1 : 0;
by asmithmd1 16y ago
I like this slick way cycle thru a range of numbers:
c = c < 4 ? c + 1 : 0;
- nostrademons 16y agoI tend to prefer c = (c + 1) % 4. It's shorter (which matters for client-side code), and makes it more explicit what you're attempting to accomplish.
- tantalor 16y agoAgreed, that is definitely more clear. Alternatively, increment with c++ and replace [c] with [c%4].
- rudasn 16y agoI really regret not paying attention to maths at school. What exactly is the % doing there? What is the purpose of % normally?
- nostrademons 16y ago% is the modulus operator. It's the remainder when you divide...so 0 % 4 == 0, 1 % 4 == 1, 2 % 4 == 2, 3 % 4 == 3, then 4 % 4 == 0 again. It's useful in that the result cycles through 0 <= x % n < n.
- tydok 16y agojust a correction. The equivalent to the above is: c = (c + 1) % 5