When coding I find myself doing the following very often:
corner++;
if(corner == 4) corner = 0;
Is there anyway do this in one line?
In this example corner should be 0, 1, 2, 3, 0, 1, 2, 3, 0....
You can use this short and kind of readable line (Demo):
corner = (corner + 1) % 4;
Or, even a tiny bit shorter (Demo):
corner = ++corner % 4;
Use remainder. It's two lines but clean.
corner++;
corner %= 4;
You can do this:
corner = ++corner == 4 ? 0 : corner;
This would give you the possibility to assign something else to the corner
variable in case your corner == 4
test didn't pass.
I use:
if (++corner == 4) corner = 0;
It is not so obvious but much faster, since division generally executes slower than any bitwise operation.
corner = ++corner & 3;
EDIT: And surprisingly I discovered one more awesome way to make cycling - using shifts, and it runs even faster!
corner = ++corner << 30 >>> 30;
And this trick only works for any power of 2.
This benchmark shows all the results (though it's javascript, not java)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With