请解释为什么Java和C给出不同的答案这个code [英] Please explain why Java and C give different answers for this code

查看:108
本文介绍了请解释为什么Java和C给出不同的答案这个code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Test
{
    public static void main(String[] args) {
        int i = 10;
        i = i++;
        System.out.println("value of i is : " + i);
    }
}

输出为: 10

当我在 C 执行类似code,输出为 11

When I executed similar code in C, output is 11.

推荐答案

对于 C 这是的未定义行为因为你要修改同一个变量不止一次相同的在这条线上顺序点

With respect to C this is undefined behavior since you are trying to modify the same variable more than once within the same sequence point on this line:

i = i++;

C99标准草案节 6.5 第2款的说道:

的previous和下一个序列点的对象应具有其存储的值之间
  由前pression评价修改最多一次
。此外,前一个值
  应仅被理解为确定值存储到

这是很好的Java定义的,它不具有相同的序列点概念c 不和Java语言规范( JLS 的)超出它的方式,以确保这样的操作定义。第 15.7 在JLS说:

This is well defined in Java, which does not have the same sequence point concept that C does and the Java Language Specification(JLS) goes out of its way to ensure such operations are defined. Section 15.7 of the JLS says:

二元运算符的左边的操作数出现在右侧操作数进行评估的任何部分前应充分评估。例如,如果左侧操作数包含一个分配给一个变量和右操作数包含对相同的变量的引用,则通过参考所产生的值将反映出发生分配第一这一事实。 [...]

The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated. For example, if the left-hand operand contains an assignment to a variable and the right-hand operand contains a reference to that same variable, then the value produced by the reference will reflect the fact that the assignment occurred first. [...]

和部分 15.7.2 说:

Java编程语言也保证了操作的每一个操作数(除有条件的运营商和放大器;?&放;, ||和:) 似乎执行自身操作的任何部分之前充分评估。

The Java programming language also guarantees that every operand of an operator (except the conditional operators &&, ||, and ? :) appears to be fully evaluated before any part of the operation itself is performed.

注意 C 没有指定求值的顺序,主要是给编译器的更好地优化选项。从标准草案 6.5 第3段的:

Note that C does not specify the order of evaluation, mainly to give the compiler better options for optimization. From the draft standard section 6.5 paragraph 3:

运算符和操作数的分组由syntax.74表示)除规定
  后来(在函数调用(),放大器;&放;, ||,?:和逗号运营商), SUBEX pressions的评价中,副作用发生的顺序和秩序都不确定的。

The grouping of operators and operands is indicated by the syntax.74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.

更新

如果你想就未定义行为对一些在Java和C之间的理念差异的讨论,你有<一个href=\"http://shape-of-$c$c.coding-guidelines.com/2012/05/14/undefined-behavior-is-a-design-decision/\"相对=nofollow>未定义行为是Java <设计决策和未定义行为/ A>

If you want a discussion on some of the differences in philosophy between Java and C with respect undefined behavior you have Undefined behavior is a design decision and Undefined behaviour in Java.

这篇关于请解释为什么Java和C给出不同的答案这个code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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