C associativity rules

Mark Jones jones at ingr.UUCP
Fri Sep 23 00:45:52 AEST 1988


In article <804 at proxftl.UUCP>, francis at proxftl.UUCP (Francis H. Yu) writes:
> In article <412 at marob.MASA.COM> samperi at marob.MASA.COM (Dominick Samperi) writes:
> >Does K&R C or the new ANSI C permit the compiler to evaluate an expression
> >like a+b+c in any order it pleases, rather than in the strict left-to-right
> >order (a+b)+c ? I've always assumed that a strict left-to-right order would
> >be used, as is the case for relational expressions like the one in the
> >following.
> >		while(i != -1 && a[i] != k)
> >			whatever ;
> 


Under ANSI, I believe that within a conditional, everything is
evalutated left to right(with precedence inforced) such that


	if((ptr = get_struct()) && ptr->type == MYTYPE)
		whatever;
and
	if(argv[0] && *argv[0] && **argv[0])
		progname = argv[0];

will work correctly, ie if get_struct returns NULL, ptr->type will not
be evaluated.  or if argv[0], *argv[0] will not be evalutated.  This
means that you can test for certain things first.  For instance:


struct Event
{
	int x,y;
}event;

	if(event.x == 100 && event.y == 150)
		do_gadget_1();
	else if(event.x == 100 && event.y == 250)
		do_gadget_2();
	else if(event.x == 200 && event.y = 45)
		do_gadget_3();
	.
	.
	.


can be done as

	if(event.y == 150 && event.x == 100)
		do_gadget_1();
	else if(event.y == 250 && event.x == 100)
		do_gadget_2();
	else if(event.x == 200 && event.y ==45)
		do_gadget_3();
	.
	.
	.

The second case eliminates the need to check and see if event.x == 100
twice, it will only be tested when event.y has been matched.  And this
is without optimizations, or make the code too unreadable.



Mark Jones

PS yes I know there is a switch statement, I know how to use it, and
this is only an example and demonstration.

PPS if the above suppostion about ANSI is wrong, I would like to know.
    is this same thing true for K&R.
		



More information about the Comp.lang.c mailing list