gpt4 book ai didi

java - 为什么赋值的左边不能是增量表达式?

转载 作者:搜寻专家 更新时间:2023-10-31 08:24:49 24 4
gpt4 key购买 nike

谁能告诉我以下Java代码中数组中“++”的含义:

   int [ ] arr = new int[ 4 ];
for(int i = 0; i < arr.length; i++){
arr[ i ] = i + 1;
System.out.println(arr[ i ]++);
}

上面代码中的 arr[ i ]++ 是什么意思,为什么我们不能这样做:

arr[ i ]++ = i + 1;

最佳答案

此处讨论的运算符称为后缀增量运算符 (JLS 15.14.2)。它被指定为如下行为:

  1. At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs.
  2. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable.
    1. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable.
    2. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored.
  3. The value of the postfix increment expression is the value of the variable before the new value is stored.

最后一点是这个问题的关键:你不能做 arr[i]++ = v; 的原因与你不能做 x++ = v;;后缀增量表达式返回一个,而不是一个变量

来自 JLS 15.1 Evaluation, Denotation and Result :

When an expression in a program is evaluated (executed), the result denotes one of three things:

  • A variable [...] (in C, this would be called an lvalue)
  • A value [...]
  • Nothing (the expression is said to be void)

赋值需要在左侧有一个变量,而值不是变量,这就是为什么你不能做 x++ = v;

来自 JLS 15.26 Assignment Operators :

The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs. This operand may be a named variable [...], or it may be a computed variable, as can result from a field [...] or an array access. [...]

以下片段显示了分配给的错误尝试,从相当微妙到更加明显:

int v = 42;
int x = 0;
x = v; // OKAY!
x++ = v; // illegal!
(x + 0) = v; // illegal!
(x * 1) = v; // illegal!
42 = v; // illegal!
// Error message: "The left-hand side of an assignment must be a variable"

请注意,您可以在赋值运算符的左侧某处使用后缀递增运算符,只要最终结果是一个变量即可。

int[] arr = new int[3];
int i = 0;
arr[i++] = 2;
arr[i++] = 3;
arr[i++] = 5;
System.out.println(Arrays.toString(arr)); // prints "[2, 3, 5]"

关于java - 为什么赋值的左边不能是增量表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2443537/

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