This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

I just find an interesting question

EVM6446

code named a.c:

#include <stdio.h>
int main()
{
    int x = 36, y = 20;
    x = x++ + y++;
    y = ++x + ++y;
    printf("x value is %d, y value is %d\n",x,y);
    return 1;
}

 

In three environments, I get two results:

1) Env: Fedora 8

   # gcc -c -o a.o a.c

   # gcc -o a a.o

   # ./a

   # x value is 58, y value is 80

2) Env: MontaVista Linux in ARM 926 using arm_v5t_le-gcc

    in Minicom, I get the result: x value is 57,y value is 79;

3)Env: Windows CCSv3.3 in C64+

     I get the same result with ARM926

 

I think the result which I get in Fedora 8 is correct. Could anyone tell me why I get the other two results?

 

Thanks.

  • This is very interesting!

    Is "1" an x86 architecture, while "2" is ARM9 and "3" is 64x+?  I appears the compilers are interpreting the statements a bit differently. 

  • The below quote in Chapter 2.12 from the book "The C Programming Language" by Brain.W..Kernighan and Dennis M. Ritchie should address your concern.

    Function calls, nested assignment statements, and increment and decrement operators cause ``side effects'' - some variable is changed as a by-product of the evaluation of an expression. In any expression involving side effects, there can be subtle dependencies on the order in which variables taking part in the expression are updated. One unhappy situation is typified by the statement

    a[i] = i++;

    The question is whether the subscript is the old value of i or the new. Compilers can interpret this in different ways, and generate different answers depending on their interpretation. The standard intentionally leaves most such matters unspecified. When side effects (assignment to variables) take place within an expression is left to the discretion of the compiler, since the best order depends strongly on machine architecture.

    The moral is that writing code that depends on order of evaluation is a bad programming practice in any language. Naturally, it is necessary to know what things to avoid, but if you don't know how they are done on various machines, you won't be tempted to take advantage of a particular implementation.

  • Yes, the first is x86, "2" is ARM9 and third one is "c64+.

    As Sivaraj said, Different compilor and different achitechure produce different result.  I don't know whether "sparc" will produce the third type of result. Let me try it. :)

  • I recommend a link " en.wikipedia.org/wiki/Sequence_point " about this quesion.  This page introduces side effects of sequece point and then tell us where we can use sequnce points when coding.

    I hope this will help us to avoid coding mistakes.

  • Lorry and Sivaraj,

    As always, thank you for contributing your findings back to this community.