编程语言
首页 > 编程语言> > C和JAVA中递增递减运算符的差异

C和JAVA中递增递减运算符的差异

作者:互联网

参见英文答案 > What is x after “x = x++”?                                    17个
>            Why are these constructs using pre and post-increment undefined behavior?                                    14个
请考虑以下声明:

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

根据我的逻辑,n应该是10.但是我在c中得到不同的输出(输出是7)
但是在java中我得到的预期结果是10.增量和减量运算符在c和java中的工作方式有什么不同.

这是我的确切c和java代码:

         #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代码: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);
     }
}

解决方法:

关于C99 draft standard 6.5.2中的C:

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.

它引用以下代码示例为未定义:

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

该部分在draft 2011 standard中也是相同的,但它看起来有点尴尬.这是sequence point的一个很好的参考.

15.7节是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

标签:post-increment,pre-increment,c-3,java,expression
来源: https://codeday.me/bug/20190728/1566650.html