Date: Sun, 23 Feb 1997 20:01:57 -0500 (EST) From: Thomas David Rivers <ponds!rivers@dg-rtp.dg.com> To: ponds!lakes.water.net!phobos.illtel.denver.co.us, ponds!lambert.org!terry Cc: ponds!freebsd.org!audit-bin, ponds!best.net!dillon, ponds!freebsd.org!FreeBSD-hackers, ponds!gvr.win.tue.nl!guido, ponds!resnet.uoregon.edu!gurney_j, ponds!sonic.cris.net!top Subject: Re: hmm Message-ID: <199702240101.UAA11182@lakes.water.net>
next in thread | raw e-mail | index | archive | help
> > On Sat, 22 Feb 1997, Terry Lambert wrote: > > > > with p="" > > > *p != '\0' && p[strlen(p) - 1] == '[' _still_ will read a byte p[-1]. > > > > What? > > > > IF p = "" > > THEN *p = '\0' > > > > by definition of ""... > > but p[strlen(p) - 1] will be p[-1] > Optimization done by compiler may skip it, but depending on that will be > rather dangerous. > > -- > Alex > > It may not be too clear... but, and at the risk of repeating what other's may have indicated - the C language, by definition, evaluates this from left to right. And, in the situation above (a logical-and) the first 0-valued expression will cause the result of the logical-and to be 0. Furthermore, the a compiler, or optimizer, is forbidden from evaluating the rest of the expression. That is, if *p is equal to '\0' - the remainder of the logical-and will not be evaluated... if an optimizer does cause this to happen, the compiler/optimizer is in error. So, if strlen(p) was 0, it wouldn't matter; p[-1] would never be referenced. In this veign you'll also often see code like: if(p != NULL && !strcmp(p,"some value") ) the left side of logical-and guarantees that the pointer 'p' is not NULL. The right side of the logical-and can then safely dereference 'p'. Again; this isn't a coincedence, C is defined (from the early K&R days) to behave in this manner. In compiler terms it's called short-circuit evaluation of logical expressions... - Dave Rivers -
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199702240101.UAA11182>