home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky comp.os.linux:10066 comp.lang.c:13296
- Newsgroups: comp.os.linux,comp.lang.c
- Path: sparky!uunet!usc!sol.ctr.columbia.edu!grunt!matthew
- From: matthew@psych.psy.uq.oz.au (Matthew McDonald)
- Subject: Re: GCC 2.2.2d bug
- Organization: Psychology Department, University of Queensland
- Followup-To: comp.lang.c
- References: <1992Sep4.202913.14346@hippo.ru.ac.za> <1992Sep4.230902.2523@novell.com> <1992Sep6.162717.24242@pool.info.sunyit.edu>
- Message-ID: <1992Sep7.114713.5075@ctr.columbia.edu>
- Sender: news@ctr.columbia.edu (The Daily Lose)
- Date: Mon, 7 Sep 1992 11:47:13 GMT
- X-Posted-From: chrysis.psy.uq.oz.au
- X-Posted-Through: sol.ctr.columbia.edu
- Lines: 58
-
- James Henrickson writes:
- |>Brendan B. Boerner writes:
- |> >In article <1992Sep4.202913.14346@hippo.ru.ac.za> pi@cs.sun.ac.za writes:
- |> >>I have found that gcc is generating the wrong code for the following
- |> >>code fragment:
- |> >>
- |> >> int p = 10;
- |> >> p = p++;
- |> >>
- |> >>From my C background, I have found the value to be 10. Unfortunately
- |> >>(for the gcc maintainers) the result is 11.
- |> >
- |> >I have this idea that if you posted this to comp.lang.c, Chris Torek or
- |> >someone similar would point out that this is correct behaviour. My gut
- |> >feeling is that it SHOULD be 11 but I'm not a C guru.
- |>
- |> Since the value of p isn't used for anything, it looks like the compiler
- |> is optimizing it for you. Here's another test:
- |>
- |> printf("%d\n",(p = p++));
- |> printf("%d\n",p);
- |>
- |> The results should, I think, be:
- |> 10
- |> 11
-
- There is no correct answer, either 10 or 11 are perfectly
- legal results. This isn't completely intuitive.
-
- When you use an operator (like =, ++, -= ...)
- that modifies the value of a variable the C compiler is under
- no obligation to put the new value into the variable immediately.
- The variable is only guaranteed to have its *new* value after the
- next end-of-statement or *logical* boolean operator, (or other
- `sequence point'.)
-
- What's happening is that the two assignments to p (p++ and p=...)
- don't have to happen in any particular order, as long as they both get
- done before the next semicolon.
-
- "p=..." (which sets p to 10) might modify p first or "p++"
- (which sets it to 11) might modify p first. You can't tell which will
- happen first and which will happen last and overwrite the value of the first.
-
- That's what the language definition says and that's what the
- compilers have done for nearly ten years now. Both Harbison & Steele
- and K&R spend a fair bit of time explaining evaluation order. If this
- confuses you, take a look in either of those.
-
- Executive summary:
- It's not a gcc bug.
- Don't modify a variable twice in the same expression.
-
- Followups to comp.lang.c
-
- =-=-
- Matthew McDonald matthew@psych.psy.uq.oz.au
- Kill the Lawyers. Boycott AT&T.
-