gpt4 book ai didi

java - 请解释为什么Java和C对此代码给出不同的答案

转载 作者:行者123 更新时间:2023-11-30 19:53:09 26 4
gpt4 key购买 nike

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

输出为:10

当我在 C 中执行类似代码时,输​​出为 11

最佳答案

对于C来说,这是undefined behavior因为您试图在同一个 sequence point 中多次修改同一个变量在这一行:

i = i++;

draft C99 standard6.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.

这在 Java 中得到了很好的定义,它没有与 C 相同的序列点概念,并且 Java 语言规范 ( JLS ) 超出了其规定确保定义此类操作的方法。节15.7 JLS 说:

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部分说:

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没有指定求值的顺序,主要是为了给编译器better options for optimization 。来自标准草案第 6.5 第 3 段:

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 之间在未定义行为方面的一些哲学差异,您可以使用 Undefined behavior is a design decisionUndefined behaviour in Java .

关于java - 请解释为什么Java和C对此代码给出不同的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18402304/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com