Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a situation in which using `i <= 2` in place of `i < 3` in loops would cause a change in behavior of the loop?

This is probably a silly question. I do a lot of data extrapolation with for loops in my applications. In almost all cases I tend to find i <= 2 easier to read/interpret than i < 3. Based on what I know they should always mean the same thing, but I'm wondering if there are special cases where they would be evaluated differently when used in a for loop. For example, if you used ++i instead of i++.

like image 460
Logarr Avatar asked Mar 17 '23 17:03

Logarr


1 Answers

Provided that i is an integer, then the expressions i<=2 and i<3 should be identical in function.
(they may be slightly different in terms of speed performance)

If i has type float, double, decimal, or related, then a value of 2.3 would fail the first test, but pass the second test.

If you specifically overload the operator< or operator<=, then you could make anything possible.

like image 98
abelenky Avatar answered Apr 27 '23 16:04

abelenky