delphi - Triple equality expression evaluation -


suppose have 3 variables , need assert can either equal -1 or neither can equal -1. wrote following code:

x := 1; y := 1; z := 1;  assert( (x = -1) = (y = -1) = (z = -1) ); 

i write kind of check, 2 variables. surprisingly triple comparison compiled too, doesn't work expected. (1, 1, 1) values expect evaluate true. after substitution of variable values , simplification get:

assert( false = false = false ); 

and thought should evaluate true, doesn't. how triple comparison evaluated?

first of all, = operator binary operator: works on pair of values. there's no such thing "triple equality". compiler evaluate 1 pair, , use result evaluate other.

when compiler sees multiple linked operators, needs group them pairs using what's called "precedence of operators". it's clear if think basic arithmetic operators learned in primary school. there's no doubt what: 3+2*4 evaluates to: it's equivalent 3+(2*4). when in doubt, add grouping yourself. if that, see expression equivalent to:

((false = false) = false), , it's obvious evaluates to:

(true = false).

what want use and operator , group initial assert this:

assert(((x = -1) = (y = -1)) , ((y = -1) = (z = -1)))

then i'd either write expression on multiple lines make and operator obvious (sql habit, know), or rewrite completely:

assert (   ((x = -1) = (y = -1))   ,   ((x = -1) = (z = -1)) ); 

or variant:

assert (   ((x = -1) , (y = -1) , (z = -1))   or   ((x <> -1) , (y <> -1) , (z <> -1)) ); 

my rule is: if takes more 1 second figure out precedence of operators, add parentheses.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -