Say we have x
which is an integer.
is there any reason to prefer x <= 1
or x < 2
? I mean if one is maybe faster or more readable.
This question is language independant, meaning if the answer is different for two different languages, please let me know.
Usually when I loop over a zero-based collection, I use i < col.Length
, as it is more readable than i <= col.Length - 1
. If I am iterating from 1 to x, I use for (int i = 1; i <= x ...)
, as it is more readable than < x + 1
. Both of theese instructions have the same time requirement (at least on x86 architecture), so yes, it is only about readability.
I would say that it depends on the requirements of your software, was it specified that x
needs to be one or less or was it specified that x
needs to be less than two?
If you ever changed x
to be of a number type that allows decimal points, which way would work best then? This happens more often than you think and can introduce some interesting bugs.
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