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

C和JAVA中递增递减运算符的差异,第1张

概述参见英文答案 > What is x after “x = x++”?                                    17个 >             Why are these constructs using pre and post-increment undefined behavior?                                    14 参见英文答案 > 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

总结

以上是内存溢出为你收集整理的C和JAVA中递增递减运算符的差异全部内容,希望文章能够帮你解决C和JAVA中递增递减运算符的差异所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1215275.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存