开发者

Ada short-circuit control forms

Whats the meaning of

x AND THEN y AND z

is it

x AND THEN (y AND z)

(y, z gets开发者_如何学Go never evaluated if x is FALSE) or

(x AND THEN y) AND z

(if x is FALSE, y is skipped, but its possible that z is evaluated) in ada?


@oenone's comment mentions that GNAT rejects x AND THEN y AND z, but doesn't explain why. It's true, in a sense, that and and and then have the same precedence, but that's not the whole story.

The grammar for an expression is:

expression ::=
  relation {and relation}  | relation {and then relation}
  | relation {or relation} | relation {or else relation}
  | relation {xor relation}

where { FOO } denotes zero or more occurrences of FOO.

This grammar is specifically designed to allow any one of these operators or control forms to be chained in a single expression (X and Y and Z, A and then B and then C), but to forbid mixing them. So the expression in the question, x AND THEN y AND z, is illegal, and the question of what it means doesn't even arise. The point of this rule is precisely to avoid confusion in cases like this.

You just need to write (X and then Y) and Z or X and then (Y and Z), whichever one matches what you want to do.

The same applies to mixing and and or:

    X and Y and Z  -- legal
    X and Y or  Z  -- ILLEGAL
    (X and Y) or Z -- legal
    X and (Y or Z) -- legal


The short-circuit operators have the same precedence as their strict versions.


As Mrab & Ira & trash have said they have equal pecedence, however what has not been pointed out explicitly is that the "and then" & "or else" operators will cause the expression to return (finish evaluation) as soon as a result can be determined.

For example(in pseudocode) :

if Almost_always_true_fn() or else costly_fn() then 
  do_stuff;
end if;

Most of the time only the first function (Almost_always_true_fn) will be evaluated, and only when that returns false will costly_fn be executed.

Compare this with :

if Almost_always_true_fn() or costly_fn() then 
  do_stuff;
end if;

In this case both Almost_always_true_fn() and costly_fn() will be evaluated.

NWS.


Yes, in (x AND THEN y) AND z, the relation z will always be evaluated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜