What does a *= b + c expand to?
Studying the standard there was no information on how this will expand. I tried it in visual studio 2008 and it does a = a * (b+c); Does the standard guarantee that it will always expand to that and not a = a * b + c? Was this always th开发者_运维技巧e way that expression expanded for all c++ standard versions?
Thanks.
Yes it's guaranteed.
a::operator*=(b + c);
EDIT:
Precedence isn't listed in a nice table in the standard, there's a footnote to 5/4
saying:
The precedence of operators is not directly specified, but it can be derived from the syntax.
The C++ Reference table is correct though.
Operators like =, *=, etc.
have (almost) the lowest precedence (see this reference).
This means that whatever expressions you have on the right side of assignment operator, those expressions will be evaluated first. Then the result of evaluation will be assigned to the variable on the left side of assignment operator (multiplying along the way, in the case of *=
).
a *= b + c
does not "expand" to anything, *=
is not a preprocessor macro.
Yes, modulo some obscure compiler bug the right side has always been evaluated as a unit.
*=
is its own operator. It should amount to the same postconditions as writing a = a * (b + c)
if the latter is valid but is not guaranteed to use the same path of execution to get there.
The +
will have a higher precedence than the *=
so it is guaranteed that b+c will be evaluated first, even if a is of a class type and *=
is an overload.
*= is a separate operator. For all the built in functions it does the same thing as multiplication and assignment, and if you ever define it for one of your own classes you really SHOULD make it do the same thing, for obvious reasons. However, you wouldn't HAVE to.
That is, *= is its own operator, with its own precedence, and internally it will be represented as "multiplication, then assignment", but at no time is the line ever re-parsed with multiplication and assignment operators in.
Given that, there's two ways that line could possibly be parsed:
- As a *= (b+c) (should have the same result as a = a * (b+c) for any sane types)
- As (a*=b) + c (which assuming this is a stand-alone statement, will do multiply a by b, assign the result to a. It will then multiply the new value by c, but it will throw the result away)
So you can see, there's no precedence which would make it do "a = (a*b)+c" which is what you feared.
In fact, the second is clearly not very useful, and for this reason, all the assignment and something-assignment operators have lower precedence than arithmetic and other "normal" operations, in fact, lower precedence than anything except ",".
It's easy to check the precedence by googling and finding a table like:
http://www.cppreference.com/wiki/language/operator_precedence
I don't remember all of the details, so it's fine to check if you're not sure between similar operators, but you can do most of it by remembering the general principles like this one.
精彩评论