In the code,
const int x = 3;
int y = 0;
y += x;
Is there any need to remove the const from x before doing the addition or is this maybe done implicitly in the addition operator definit开发者_开发百科ion?
Firstly, the +=
operator is an assignment operator (compound assignment). Its behavior though is equivalent to y = y + x
combination (except y
is evaluated only once).
Secondly, when used as an operand of addition operator (including the RHS of +=
as in your example) x
participates in the expression as an rvalue, i.e. it is implicitly subjected to so called lvalue-to-rvalue conversion. This conversion immediately discards const
, since rvalues of non-class types (int
in your case) cannot be cv-qualified.
Done implicitly, since you're not going to change x
.
There is no need to remove const
if x
is used only as in given snippet.
The const
modifier marks one variable as holding read-only data. If the compiler sees that you are modifying it, it will get angry and report an error. For all other uses, const
is dropped.
In your case, you aren't modifying x
so there's no need for const
removal.
精彩评论