Evaluation of if's

Craig A. Finseth fin at norge.unet.umn.edu
Sat Jun 15 01:41:21 AEST 1991


In article <1991Jun13.184843.508 at ulkyvx.bitnet> pgheit01 at ulkyvx.bitnet writes:
>In article <1991Jun7.232119.17834 at cs.ucla.edu>, jon at maui.cs.ucla.edu (Jonathan Gingerich) writes:
>> 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.

>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)
	...

Correct.

>The statement if ((i = 1) == (i = 2)) is valid.  ANSI C evaluates conditions 

Not correct.  Even though the sub-parts of the expression, taken
separately, are valid, it does not follow that the entire statement is
valid.

>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

[ Digression about short-circuit evaluation of && and || and
precendence omitted.  Irrelevant to this question. ]

>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.

ANSI says that the expression is undefiend.  A compiler behaving as
you described does not violate the standard.  When arguing that a
particular behavior should be defined, it is *never* useful to cite
any particular implementation or collection of implementations.

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

I'm glad that your teacher is concentrating on these pressing issues.
He or she certainly wouldn't want to get involved in such messy issues
as what it means to conform to standards, the meaning of "undefined,"
or other portability-related issues.  [Many (:-)s for those of you who
couldn't deduce them from the wording.]

Craig A. Finseth			fin at unet.umn.edu [CAF13]
Networking Services			+1 612 624 3375 desk
University of Minnesota			+1 612 625 0006 problems
130 Lind Hall, 207 Church St SE		+1 612 626 1002 FAX
Minneapolis MN 55455-0134, USA



More information about the Comp.lang.c mailing list