Re: C and side-effects

From: Sandy Harris (sandy@storm.ca)
Date: Wed May 03 2000 - 21:12:09 EST


"Robert M. Love" wrote:
>
> > Rik van Riel wrote:
> >
> > > I'm not that good at C, mas aren't expressions with side-effects
> > > ill-defined? How can we be sure (short of tracking the gcc
> > > mailing lists) that i will be incremented after the left part of
> > > the test?
> >
> > Because it is defined in the C standard?
> >
> > Rik
>
> maybe im reading the thread wrong, but Cesar is saying the code
> while ((mm->swap_cnt << 2 * (i + 1) < max_cnt) && i++ < 10)
> does not guarentee that the expression to the left of && occurs prior to
> "i++" -- and he is Right,
> because the C standard does *not* specify this. proof is in K&R, where they
> explicitly mention compiler design or optimization can change compound
> statement ordering in the resulting machine code. thus, i agree an
> alternative should be considered in the kernel.
>
No. They explicitly state that in, for example:

        x = y() + z() ;

the compiler is free to call the functions y() and z() in either order
Also in:

        x = a( y(), z() ) ;

And it gets worse in some cases. Either of these for example:

        x = y(i) + i++ ;
        x = z(i, i++) ;

can produce quite different results depending what order the compiler
chooses. Such code should be carefully avoided. If there were anything
like that in the kernel, finding an alternative would be mandatory.

But for the && and || operators K&R and the standards equally explicitly
guarantee 'shortcut evaluation':

        x = y() && z() ;

guarantees that y() is called and if it returns 0 then x becomes 0
and z() is not called.

        x = y() || z() ;

guarantees that y() is called and if it returns non-0 then x becomes
non-0 and z() is not called.

Arguably there may be stylistic or readability problems with the
quoted line, but it is definitely legal.

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.rutgers.edu
Please read the FAQ at http://www.tux.org/lkml/



This archive was generated by hypermail 2b29 : Sun May 07 2000 - 21:00:13 EST