Order of evalution of expressions.

leland.f.derbenwick lfd at cbnewsm.att.com
Thu Sep 20 02:41:55 AEST 1990


In article <6398 at castle.ed.ac.uk>, elee24 at castle.ed.ac.uk (H Bruce) writes:
> I have lost my FAQ files but I'm certain this is not on it....
> 
> Is the line
> 
> value = *ptr - *ptr++;
> 
> sensible C ?
> In other words is there a specified order of evaluation of expressions ?

Not in this case.

> If not then the answer would depend on when the increment is done.
> 
> If not what is the fastest way of computing this type of expression ?

Assuming ptr does not point to a volatile value (e.g., a hardware
status register), then there's a trivial optimization:

  value = 0;  ptr++;

If it really requires two reads of *ptr, then the order of the reads
is also important, and your other approach should be taken:

> value = *ptr;
> value -= *ptr++;

Note that

  value = *ptr - *ptr;  ptr++;

is _not_ equivalent, since there is no guarantee which "*ptr" access
is done first: this could give either the initial value minus the
final value, or the final value minus the initial value.

Also, if the value being read is volatile, it must be declared so
(in ANSI-compatible compilers) or optimization must be turned off
(in older compilers).  Some compilers won't optimize the two reads
of *ptr away anyhow, but it's extremely risky to assume that.

 -- Speaking strictly for myself,
 --   Lee Derbenwick, AT&T Bell Laboratories, Warren, NJ
 --   lfd at cbnewsm.ATT.COM  or  <wherever>!att!cbnewsm!lfd



More information about the Comp.lang.c mailing list