سؤال

Please consider the following statement:

int a[]={1,2,3,4,5,6,7,8};
int i=0,n;
n=a[++i] + i++ + a[i++] + a[i] ;

According to my logic n should be 10. But I am getting different output in c (output is 7) However in java I am getting expected result that is 10. Is there any difference in the way in which increment and decrement operators work in c and java.

Here is my exact c and java code:

         #include <stdio.h>
            int main()
            {
                int a[]={1,2,3,4,5,6,7,8};
                int i=0,n;
                n=a[++i] + i++ + a[i++] + a[i] ;
                printf("%d",n);
                getch();
                return 0;
            }

Java code with output : 10

public class HelloWorld{

     public static void main(String []args){

        int a[]={1,2,3,4,5,6,7,8};
        int i=0,n;
        i=0;
        n=a[++i] + i++ + a[i++] + a[i] ;
        System.out.println(n);
     }
}
هل كانت مفيدة؟

المحلول 2

With respect to C from the c99 draft standard 6.5.2:

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.

it cites the following code examples as being undefined:

i = ++i + 1;
a[i++] = i; 

The section is same in the draft 2011 standard as well but it reads a bit more awkward. This is a good reference on sequence point.

Section 15.7 is the relevant section from the JLS:

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect

نصائح أخرى

In C, that's an undefined behaviour. Since C doesn't guarantee the order of evaluation of individual operation in an expression.

To add to Rohit's answer, if you do each of the steps separately, the answer 10 is given. This just highlights that the execution of i++ and ++i may not be happening in the order the arguments are being added to the value n.

#include <stdio.h>
int main()
{
    int a[]={1,2,3,4,5,6,7,8};
    int i=0,n;
    n=a[++i] + i++ + a[i++] + a[i] ;
    printf("%d\n",n);

    i=0;
    n=0;
    n=a[++i];
    printf("%d\n",n);
    n+=i++;
    printf("%d\n",n);
    n+=a[i++];
    printf("%d\n",n);
    n+=a[i];
    printf("%d\n",n);
    return 0;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top