On Mon, Jul 20, 2009 at 10:30 AM, <i...@adari.net> wrote:
> Hello,
>
> Here is a program with output in gcc (4.3.2) on pre and post increments:
>
> //--------------------code begin--------------------------------------------
> #include <stdio.h>
>
> main () {
>    int a;
>    a=1; printf ("1. %d %d\n", ++a, a);                     // 1. 2 2
>    a=1; printf ("2. %d %d\n", a, a++);                     // 2. 2 1
>    a=1; printf ("3. %d %d\n", a++, a);                     // 3. 1 2
>    a=1; printf ("4. %d %d\n", a++, ++a);                   // 4. 2 3
>    a=1; printf ("5. %d %d\n", ++a, a++);                   // 5. 3 1
>    a=1; printf ("6. %d %d %d\n", ++a, a, a++);             // 6. 3 3 1
>    a=1; printf ("7. %d %d %d\n", a++, a, ++a);             // 7. 2 3 3
>    a=1; printf ("8. %d %d %d %d\n", a, a++, ++a, a);       // 8. 3 2 3 3
>    a=1; printf ("9. %d %d %d %d\n", a, ++a, a++, a);       // 9. 3 3 1 3
>    a=1; printf ("10. %d %d %d %d %d\n", a, a++, a, ++a, a);// 10. 3 2 3 3 3
>    a=1; printf ("11. %d %d %d %d %d\n", a, ++a, a, a++, a);// 11. 3 3 3 1 3
> }
> //--------------------code end--------------------------------------------
>
> The output from the program is listed next to it in comments. I thought
> I knew something about pre and post increments, but this program busted
> my understanding of the pre and post increments. I would appreciate
> if someone could explain me the output.
>
> Thanks
>
>
>


The order in which the compiler evaluates arguments to a function is
up to the implementation.  It can do it left to right, right to left,
start in the middle and spiral its way out, do them all in parallel,
or anything else that's convenient from an implementation standpoint.
So if a=5 before a function call, then foo(++a, ++a), might invoke
foo(6, 6), foo(6, 7), or foo(7, 6).

The only way to be totally safe is to either only use const operations
as arguments to a function (assuming of course they don't violate
their const-ness), or perform all operations before a function call
and pass in raw variables / data.

Reply via email to