More likely x <= 1 or x <2?

Say we have x , which is an integer.

Is there any reason to prefer x <= 1 or x < 2 ? I mean, if someone is perhaps faster or readable.

This question is language independent, that is, if the answer is different for two different languages, please let me know.

+5
source share
3 answers

Usually, when I i < col.Length over a null set, I use i < col.Length , as it is more readable than i <= col.Length - 1 . If I repeat from 1 to x, I use for (int i = 1; i <= x ...) , as this is more readable than < x + 1 . Both of these instructions have the same time requirement (at least on the x86 architecture), so yes, this is read only.

+2
source

I would say that it depends on the requirements of your software, was it indicated that x should be one or less, or was it indicated that x should be less than two?

If you have ever changed x to a type of number that allows decimal points, how will it work best? This happens more often than you think, and you can introduce some interesting errors.

+1
source

In general, there is no evidence of what types the literals 1 and 2 have. In most languages ​​they will be the same, but in theory they can be different, and the results of two comparisons can be different. In addition, integers are not infinite in most languages, so behavior may differ from borders.

In plain C, if comparisons x <= -0x80000000 and x < -0x7fffffff (note that -0x80000000 < -0x7fffffff ) and x are of type int , the results depend on the value of x:

 -0x80000000 : 1 1 -0x7fffffff .. -1 : 0 0 0 .. 0x7fffffff: 1 0 

In other words, for all non-negative x results will be different.

Similarly, when comparing x <= 0x7fffffff and x < 0x80000000 (the ratio between the constants 0x7fffffff < 0x80000000 preserved), we obtain:

 -0x80000000 .. -1 : 1 0 0 .. 0x7fffffff: 1 1 

Now the results are different for all negative x values.

Obviously, there are some rules for input and type conversion (they are described in the C language standard), but the fact is that two comparisons cannot be replaced by boundary cases.

0
source

Source: https://habr.com/ru/post/1268973/


All Articles