Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rather 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 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.

like image 646
Null User Avatar asked Oct 18 '22 10:10

Null User


2 Answers

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.

like image 87
Dmitry Pavlushin Avatar answered Oct 21 '22 07:10

Dmitry Pavlushin


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.

like image 40
ridecar2 Avatar answered Oct 21 '22 07:10

ridecar2