Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When possible, should a programmer always use < rather than <=?

Consider the two for-loop declarations:

for (int i = 0; i < 70; ++i)

and

for (int i = 0; i <= 69; ++i)

I'm assuming the second one is going to make 139 total comparisons rather than 69. Is my assumption correct? I'm not an electrical engineer, so I don't know how an ALU actually works, whether it does a "less than or equals" thingamabob in one fell swoop or what.

Can you give an example of when using a <= is justified?

By the way, I'm trying to become a "hardcore" programmer like you guys are.

like image 963
Premature Optimizer Avatar asked Feb 13 '23 06:02

Premature Optimizer


2 Answers

There's no right or wrong answer here.

Different loops will have different requirements. Sometimes you will use < and sometimes you will use <=. Other times you will use >!

Oh god, the possibilities! You could use && or || or ...

Sometimes you won't even use an operator at all! You could use the value of a variable!

Or the return value of a function!

Or... a boolean!


Also, please look into short-circuit evaluation.

Given the following logical expression

9 < 10 || 9 == 10

only 1 comparison will be made because the first half is true.

I would trust that <= is optimized accordingly.

like image 97
Mulan Avatar answered Feb 15 '23 20:02

Mulan


The relevant thing is not whether using '<' or '<=', that's irrelevant.

The important thing is whether 70 or 69 is the important thing in your program.

That is, if your array has 70 elements, then the most logical course of action is to write 70, and use the according operand.

For example, in languages with 1-based arrays you will write:

for i = 1, i <= 70

but in 0-based arrays:

for i = 0, i < 70
like image 31
rodrigo Avatar answered Feb 15 '23 21:02

rodrigo