Home > Software design >  Using >= or value - 1?
Using >= or value - 1?

Time:11-15

Say I'm checking for if a value is greater than or equal to a certain value and the current values I'm comparing are integers. In C , would it be more optimal to do something like:

if(value > threshold - 1)
...

or this

if(value >= threshold)
...

My thinking is that the call to >= adds an extra stack frame, but then again a call is made when using - for the subtraction operation. While I know the performance difference is likely negligible, which is technically more optimal?

CodePudding user response:

The first has undefined behavior if threshold is signed and is the most negative value of its type. That might disqualify it immediately, but if you know that case is impossible, it is therefore at least as fast as the >= version since the compiler is obliged to produce the same answer but in only a subset of cases. In practice, however, equivalent assembly is produced: any sensible architecture has enough comparison instructions such that some combination of swapping the inputs and switching between strict and non-strict inequalities can implement either without actually subtracting 1.

If threshold is unsigned, the first is well-defined for all input values but is inequivalent to the >= version. Again, that inequivalence might compel the choice; otherwise, the first is slower on typical architectures because it actually has to perform the subtraction to achieve that difference in behavior.

CodePudding user response:

If threshold is the smallest repersentable value, then threshold - 1 will have the wrong behaviour (opposite of desired behaviour [assuming desired behaviour is what >= provides] if unsigned, or undefined behaviour if signed). >= doesn't have this problematic corner case.

Another consideration is that value >= threshold has the same behaviour for floating point, while the behaviour of - 1 is different. This makes >= more general.

  • Related