Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in Increment-decrement operator in C and JAVA [duplicate]

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);
     }
}
like image 924
Abhas Tandon Avatar asked Oct 25 '25 15:10

Abhas Tandon


1 Answers

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

like image 155
Shafik Yaghmour Avatar answered Oct 27 '25 04:10

Shafik Yaghmour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!