C和JAVA中增量递减运算符的差异 [英] Difference in Increment-decrement operator in C and JAVA

查看:178
本文介绍了C和JAVA中增量递减运算符的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下声明:

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中,增量和减量运算符的运行方式有差异。

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.

这是我的确切的c和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代码:10

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);
     }
}


推荐答案

对于 c99 c> 标准草案 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; 

该部分在 2011年草案标准,但它读起来有点尴尬。这是序列点的好参考。

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.

部分 15.7 JLS 中的相关部分:


Java编程语言保证操作符的操作数似乎以特定的评估顺序进行评估,即从左到右。

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

这篇关于C和JAVA中增量递减运算符的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆