Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!samsung!zaphod.mps.ohio-state.edu!mips!orac!rex From: rex@mips.COM (Rex Di Bona) Newsgroups: comp.sys.mips Subject: Re: compiler bug Message-ID: <36721@mips.mips.COM> Date: 6 Mar 90 04:58:16 GMT References: <18302@shamash.cdc.com> Sender: news@mips.COM Reply-To: rex@mips.COM (Rex Di Bona) Organization: MIPS Computer Systems, Sunnyvale, CA Lines: 76 In article <18302@shamash.cdc.com> dwl@mercury.udev.cdc.com (Daren W Latham) writes: >I have just run across what I believe is a bug in the C compiler. It doesn't >matter if optimization is turned on or not. This program works correctly with >other C compilers. Does anybody (mips perhaps) know if this bug is documented, >or just what the status of this is. I am running on: This is not a "bug". What you have done is illegal under `standard' C. You have two side effects in the one line that refer to the same variable. This usually gives "undefined" results, and is a common source of errors. This is because the order in which the side effects are done in relation to the rest of the code is undefined. Reference: "K&R Section 2.12" (Both first, and second (ansi) editions) >#define PushArg(n) argStack[argStackP++] = n >#define PopArg() argStack[--argStackP] > >main() >{ > int argStack[10]; > int argStackP = 0; > int temp; > > PushArg(5); > PushArg(8); > > temp = PopArg() + PopArg(); This is the line in question. This is it after the preprocessor is done with it. temp = argStack[--argStackP] + argStack[--argStackP] The compiler produces the following for this line: (non optimised) # 24 temp = PopArg() + PopArg(); addu $13, $12, -1 sw $13, 28($sp) addu $14, $13, -1 sw $14, 28($sp) mul $15, $14, 4 addu $24, $sp, $15 lw $24, 32($24) addu $25, $24, $24 sw $25, 24($sp) The compiler has decided to do the two decrements first (this is legal) and has then removed the second lookup in the array to save a multiply. It has finally done the addition. > > printf ("temp = %d \n", temp); > > PushArg(5); > PushArg(8); > > temp = PopArg(); > > temp += PopArg(); > > printf ("temp = %d \n", temp); >} The second version forces the two decrements to be done in the order you expected. The side effects have to be completed before the next line is executed, and so you get both elements. I hope this helps. Rex. -- Rex di Bona Penguin Lust is NOT immoral! rex@mips.com apply STD disclaimers here.