Reputation: 20774
What does the C standard (preferably C89,90) say about:
int a,b;
a = 4;
b = (a += 1);
?
I have tested it and the result is b=5
, which is what I expect. I just want to be reassured by the Standard. The same applies to analogous operators like *=
, /=
, &=
, etc. I know that =
is sure to return the value of the left hand side after the assignment. I just want to know if +=
, *=
, etc. behave the same way, according to the standard.
Upvotes: 1
Views: 1168
Reputation: 387
This should result in b = 5
and a = 5
.
This is because a+=1
takes a
and adds 1
to it. Then it assigns a
to b
.
I'm kind of confused on your question, but *=
, /=
, -=
all work the same way.
For example, you could just have int c = 7
; then on the next line do c*=3
. This will make c = 21
. If in your example, you didn't want a = 5
; then just don't do a+=1
, and instead, do a+1
.
Upvotes: 0
Reputation: 10096
Assignment operators do not "return" a value: they yield one, or as the standard puts it, have one.
The value is of the left operand, although it won't be an lvalue. Here's the excerpt:
(3.3.16) An assignment expression has the value of the left operand after the assignment, but is not an lvalue.
All of = *= /= %= += -= <<= >>= &= ^= |=
are assignment operators so they behave the same way in this regard.
Upvotes: 4
Reputation: 12335
It is not a problem unless there are side-effects.
The assignment operator is not a sequence point, which means that there is no guarantee on order of evaluation.
If you use it as you have given (b = (a += 1);
), it is not a problem.
However, in other cases, it may be a problem, for example:
b = (a += 1) + a; // undefined
Notice that in this example, the variable a
is referred to twice. What that means is that we don't know whether (a += 1)
or a
is evaluated first. So we don't know if the 2nd reference to a
will be before or after 1
was added to it.
If you only refer to each variable you assign with +=
and co. once, then side-effects are not a problem, and you can count on +=
and related operators to return the value after assignment.
Upvotes: 1