News:

Let's find out together what makes a PIC Tick!

Main Menu

Best way to OR / AND multiple If-Then statements?

Started by trastikata, Apr 03, 2024, 09:43 AM

Previous topic - Next topic

trastikata

Hello,

what would be the best way to OR or/and AND multiple If-Tehn statements? AND-ing is pretty straightforward by just nesting multiple If-Then but making combinations of OR and AND gets quite complex since we can't use complex logic expressions?

For example:

If ((fTemp1 = fTemp2) AND (fTemp3 = fTemp4)) Or ((fTemp1 > fTemp2) And (fTemp3 < fTemp4)) Then ...

Frizie

In these cases I compile all options and see what needs the least code.
It is not always said that this is the fastest code, but usually it does not matter.

I should do:
XX = False
If ((fTemp1 = fTemp2) And (fTemp3 = fTemp4)) Then XX = True
If ((fTemp1 > fTemp2) And (fTemp3 < fTemp4)) Then XX = True
If XX = True Then...
Ohm sweet Ohm | www.picbasic.nl

keytapper

I think it should be possible to use Select/End Select.
Ignorance comes with a cost

tumbleweed

If ((fTemp1 = fTemp2) And (fTemp3 = fTemp4)) Or ((fTemp1 > fTemp2) And (fTemp3 < fTemp4)) Then
Since AND has priority over OR, in this case that could be written without the parenthesis as
If fTemp1 = fTemp2 And fTemp3 = fTemp4 Or fTemp1 > fTemp2 And fTemp3 < fTemp4 ThenI can understand being reluctant to do that though... it's difficult to see what's going on and to trust it.


I'd be inclined to use Frizie's method, but with one change - add an ELSEIF instead of just two IF's
XX = False
If fTemp1 = fTemp2 And fTemp3 = fTemp4 Then
    XX = True
Elseif fTemp1 > fTemp2 And fTemp3 < fTemp4 Then
    XX = True
Endif
If XX = True Then
    ' condition is true code
Endif
That can be faster since it allows you to short-circuit the second test if the first part evaluates as true.

Both of the other methods will evaluate all four comparisons, so if the conditions have side-effects they will always occur. Depends on your intent...