Evaluation of if's

pgheit01 at ulkyvx.bitnet pgheit01 at ulkyvx.bitnet
Fri Jun 14 08:48:43 AEST 1991


In article <1991Jun7.232119.17834 at cs.ucla.edu>, jon at maui.cs.ucla.edu (Jonathan Gingerich) writes:
> Having raised exactly this subject several months ago, let me point out
> that both sides are making valid points.  There are two distinct things
> going on:
> 
> 1. The description of the value of an assignment expression is sufficiently
>    ambiguous in both K&RI and ANSI as to make the variability of
> 	((i=1)==(i=2))
>    a reasonable question.  This is not directly answered in the FAQ.  It is
>    not a `order of evaluation' question. It is not obvious.
> 
> 2. There is no question that there is a rule in ANSI only, which says that
>    expression which access the same location more than once are undefined.
>    The above expression is undefined as is any other expression (to the
>    best of my knowledge) that would illustrate a difference in the evaluation
>    of an assignment expression.
> 
> Jon.


AAAAAARRRRRGGGGHHHHH!

Here's how ANSI C works.  An expression (ANY EXPRESSION) returns a value in
much the same way as a function returns a value.  The expression (i = 2)
returns the value 2.  The expression (i = 1) returns the value 1.  No if's,
and's or entry points or any of that stuff.

The statement if ((i = 1) == (i = 2)) is valid.  ANSI C evaluates conditions 
from left to right. *ALWAYS* ANSI C short-circuits a conditional statement
*ALWAYS* (unless you tell it not to) That makes possible the type of statment

if ((x != 0) && (1/x < 9))
  STATMENT;
(note that the inner sets of parentheses are not needed, and "< 9" could be
changed to whatever you need to test. Also "x != 0" can just be "x".)

ANSI guarratees that the second statement will not be executed(and division by
zero will not result) because the statment is false after the first condition
if x == 0.

I did compile and run the code in question.  The assignments do take place. 
i takes on the value 1 after the first condition is "tested", and i takes on
the value 2 after the second condition is tested.  After the if-statement is
executed, i is and will irrepairably be 2.

My C teacher just loved to slip in questions like this one to see if anyone
knew the finer details of the precedence table. :-)

Paul == pgheit01 at ulkyvx.bitnet 

Disclaimer: How could U of L really accept anything this well-defined as an
official policy?



More information about the Comp.lang.c mailing list