为什么= +不会导致编译错误? [英] Why does =+ not cause a compile error?
问题描述
在错误的代码中误用了=+
而不是+=
的人出现,并且没有显示为编译错误.
Came across someone mistakenly using =+
instead of +=
in their code and it didn't show up as a compile error.
这是因为
int a =+ 2;
与
int a = 0 + 2;
?
推荐答案
没有编译错误,因为+
是有效的(虽然相当无用)一元运算符,其作用方式与-
是:
There's no compilation error because +
is a valid (albeit fairly useless) unary operator in the same way that -
is:
int x = +1;
int y = -1;
Java语言规范中的相关部分是一加运算符+(§15.15.3).它指定调用一元+
操作会导致操作数的一元数值提升(§5.6.1).这意味着:
The relevant section in the Java Language Specification is Unary Plus Operator + (§15.15.3 ). It specifies that invoking the unary +
operation results in Unary Numeric Promotion (§5.6.1) of the operand. This means that:
If the operand is of compile-time type
Byte
,Short
,Character
, orInteger
, it is subjected to unboxing conversion (§5.1.8). The result is then promoted to a value of typeint
by a widening primitive conversion (§5.1.2) or an identity conversion (§5.1.1).
否则,如果操作数是编译时类型Long
,Float
或Double
,则将对其进行拆箱转换
(§5.1.8).
Otherwise, if the operand is of compile-time type Long
, Float
, or Double
, it is subjected to unboxing conversion
(§5.1.8).
否则,如果操作数是编译时类型byte
,short
或char
,则通过加宽将其提升为类型int
的值
原始转换
(§5.1.2).
Otherwise, if the operand is of compile-time type byte
, short
, or char
, it is promoted to a value of type int
by a widening
primitive conversion
(§5.1.2).
否则,一元数值操作数将保持不变,并且不会进行转换.
Otherwise, a unary numeric operand remains as is and is not converted.
无论如何,值集转换 (§5.1.13) 然后应用.
In any case, value set conversion (§5.1.13) is then applied.
简而言之,这意味着
- 数字原始包装器类型为未装箱,并且; 小于
- 整数类型被加宽到
int
.
int
的- numeric primitive wrapper types are unboxed, and;
- integer types smaller than
int
are widened toint
.
这篇关于为什么= +不会导致编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!