加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:46:21 所属栏目:百科 来源:网络整理
导读:参见英文答案 What is x after “x = x++”?????????????????????????????????????17个 ???????????? Why are these constructs using pre and post-increment undefined behavior?????????????????????????????????????14个 请考虑以下声明: int a[]={1,2,
参见英文答案 > 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,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,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读