Path: utzoo!attcan!uunet!samsung!usc!ucsd!rutgers!att!cbnewsm!lfd From: lfd@cbnewsm.att.com (leland.f.derbenwick) Newsgroups: comp.lang.c Subject: Re: Order of evalution of expressions. Summary: Optimized! Message-ID: <1990Sep19.164155.9422@cbnewsm.att.com> Date: 19 Sep 90 16:41:55 GMT References: <6398@castle.ed.ac.uk> Organization: AT&T Bell Laboratories Lines: 43 In article <6398@castle.ed.ac.uk>, elee24@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@cbnewsm.ATT.COM or !att!cbnewsm!lfd