Path: utzoo!attcan!uunet!aplcen!uakari.primate.wisc.edu!sdd.hp.com!hp-pcd!hpcvia!brianh From: brianh@hpcvia.CV.HP.COM (brian_helterline) Newsgroups: comp.lang.c Subject: Re: stack quirk? Message-ID: <31530012@hpcvia.CV.HP.COM> Date: 27 Jul 90 14:54:26 GMT References: <4047@pikes.Colorado.EDU> Organization: Hewlett-Packard Co., Corvallis, Oregon Lines: 49 >Hi everyone. Here's one. I hope it is not as simple as my last one, >you remember( gets() ). I'm running the following program, and I'm not >getting out what I think I should be( so what else is new!). Any ideas? >#include >main() >{ >int i= 0; >printf("\n%d %d\n", ++i, ++i); /* output is: 2 1, I expected 1 2 */ >i= 0; >printf("%d %d\n", ++i, i++); /* output is: 2 0, I expected 1 1 */ >i= 0; >printf("%d %d\n", i++, ++i); /* output is: 1 1, I expected 0 2 */ >i= 0; >printf("%d %d\n", i++, i++); /* output is: 1 0, I expected 0 1 */ >} > >Please send e-mail: ndimas@pikes.denver.colorado.edu > > > Thank You > Nicholas Dimas >---------- The output you got should is correct. The arguments to printf() [or any function] are pushed on to the stack right to left so they are in the correct order for printf() to pop them off when needed. If you evaluate each expression above right-to-left, you will "expect" exactly what the output was. Also note that each argument to printf() is a single expression, so once it is evaluated, the ++ operator can do the increment and then move on to the next expression. As an example, printf( "%d %d\n", i++, ++i ); arg1 = "%d %d\n" arg2 = i++; arg3 = ++i; if i=0 to start, and we evaluate right-to-left, arg3 = 1 and i = 1 arg2 = 1 and _then i = 2 arg1 = "%d %d\n"; I am not certain as to what ANSI specifies about whether this behavior is correct or not. I am just trying to describe what is happening. It is usually a bad idea to use ++ operators on the same variable more than once in _ANY_ expression. Hope this helps,