PBasic's MIN and MAX operator precedence.
Martin_H
Posts: 4,051
In many programming languages MIN and MAX are functions, so the order of operations is clear. But in PBasic they are binary operators, so I assume they have operator precedence. Look at this code for example:
Basically, my question is how do MIN and MAX fit into the order of operators precedence?
byte a byte b byte c a = 1 b = 2 c = 3 // All MAX is a slam dunk, it should display 3 DEBUG a MAX b MAX c // If this is evaluated left to right it should output 2. DEBUG a MAX b MIN c // But what happens when you mix in other mathematical operators? DEBUG a MAX b + 1 MIN c // What about multiply which takes precedence over other operators? DEBUG a MAX b * 2 MIN c
Basically, my question is how do MIN and MAX fit into the order of operators precedence?
Comments
-Phil
I can't believe I've been using PBasic for six years and hadn't noticed that by now. I always assumed it was like other languages which attempt to reproduce the mathematical precedence. Since I tend to avoid compound expressions and heavy math in PBasic I've gotten lucky up to now.
but the answer is 1, not 3. That is because the MAX operator sets a ceiling.
You can think of it as,
y = x MAX 3
and that is either x or 3, whichever is less. So 3 is the ceiling.
Okay, but it is equally true that
y = 3 MAX x
is either x or 3, whichever is less. The same as above. The operator is said to be commutative. So with your set of values a=1, b=2 and c=3, the MAX operator ends up picking the minimum value. Tricky huh?
OK I was completely confused. I thought these were like the C functions of the same name, but it sounds like they are reversed. In C max (1, 3) returns 3, while min(1, 3) returns 1. I have a minor rewrite to do.
-Phil