java 赋值的左边必须是变量_java – 为什么赋值的左边不能是增量表达式?

这里讨论的运算符称为后缀增量运算符(

JLS 15.14.2).它被指定为表现如下:

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.

Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable.

Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable.

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.

The value of the postfix increment expression is the value of the variable before the new value is stored.

最后一点是这个问题的关键:为什么你不能做arr [i] = v;与你不能做x = v;的原因完全相同;后缀增量表达式返回一个值,而不是一个变量.

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;.

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]"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值