Came across someone mistakenly using =+
instead of +=
in their code and it didn't show up as a compile error.
Is this because
int a =+ 2;
is the same as
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;
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).Otherwise, if the operand is of compile-time type
Long
,Float
, orDouble
, it is subjected to unboxing conversion (§5.1.8).Otherwise, if the operand is of compile-time type
byte
,short
, orchar
, it is promoted to a value of typeint
by a widening primitive conversion (§5.1.2).Otherwise, a unary numeric operand remains as is and is not converted.
In any case, value set conversion (§5.1.13) is then applied.
In short, this means that
int
are widened to int
.There may be a bug lurking here. The writer may have intended to write a += 2;
In the original version of C, a += 2;
and a =+ 2;
were synonyms. If you meant a = +2;
, you had to be careful to leave a space between the =
and the +
. Same with all the other operators. a=*p;
multiplied a by p. a = *p;
de-referenced the pointer p and assigned the result to a.
Then they came to their senses, and started giving warnings for =op
where op=
was probably intended, and now no longer accept =op
at all.
But old habits die hard. An old-school C programmer might might still absent-mindedly use old-school syntax, even when writing in a language other than C.
On the other hand, the =
in int x =+ 2;
is an initialization, not an assignment, and it would be bizarre for a programmer to think in terms of incrementing a variable that is only just now being given its initial value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With