Evaluation of if's

Chris Torek torek at elf.ee.lbl.gov
Fri Jun 7 16:12:34 AEST 1991


[Original code contained two stores to the variable `i' without an 
intevening sequence point.]

>>... all bets are off, since the Standard says that this is not allowed
>>and that anything can happen if you do it.

In article <1991Jun7.011938.11342 at wdl1.wdl.loral.com>
bard at cutter.ssd.loral.com (J H Woodyatt) writes:
>I might submit to you that all bets are off concerning the value stored
>in `i' after the expression is evaluated, but as for the result of the
>expression, if *that* is undefined, then it isn't by any means intuitive.

Perhaps so; but when the result of an operation is undefined (as here),
the behaviour of the system may be completely arbitrary.  A compiler is
entirely free to compile

	if ((i = 1) == (i = 2))
		printf("hey\n");

as if it were

	printf("you dummy!\n");

>And, by the way, I *have* a copy of the FAQ, and I *have* read it. I am
>quite aware of the problem of side effects with order of evaluation; I
>think the side effect in the above expression renders the value of `i'
>undefined, *not* the result of the expression.

Nope.  The whole thing is undefined.  The system is allowed to turn into
a skunk, or fly to the moon.  *ANY*thing might happen (although betting
on one of the preceding possibilities is unwise :-) ).

>I also have a related question. Given the following:
>
>extern volatile int k;
>if (k = 1) /* Yes, this is an assignment, not an equivalence test */
>    { .... }
>
>I would expect that it is undefined whether the block after the `if'
>expression will be executed. Am I right?

No and yes.  The value of an assignment is the value of the right hand
side, converted to the type of the left hand side.  In particular, this
strongly suggests---it cannot `mean' as the `meaning' of volatile is up
to the implementation, but it can calmly `suggest' while swaying a ten
ton mallet over the implementation's head---this suggests that, given

	int i;
	volatile int *p;
	i = *p = 3;

`i' should have the value 3, and the generated code should store a value
at *p but not read any value from *p.
-- 
In-Real-Life: Chris Torek, Lawrence Berkeley Lab CSE/EE (+1 415 486 5427)
Berkeley, CA		Domain:	torek at ee.lbl.gov



More information about the Comp.lang.c mailing list