I'm trying to use +=
to add multiple numbers to a variable.
I'm trying to do something like this:
score += var1, var2, var3
However, the only thing I know how to do now is
score += p;
score += v;
score += t;
I'm trying to use +=
to add multiple numbers to a variable.
I'm trying to do something like this:
score += var1, var2, var3
However, the only thing I know how to do now is
score += p;
score += v;
score += t;
This expression statement
score += var1, var2, var3;
is a statement with the comma operator expression.
It is equivalent to
( score += var1 ), ( var2 ), ( var3 );
So the variable score
will be incremented only by var1
.
You could write instead
score += var1 + var2 + var3;
But if you have many variables or values that you need to add to the variable score
then you can use an initializer list as for example
for ( const auto &item : { var1, var2, var3, var4, var5 } )
{
score += item;
}
@cigen's answer is perfect, but lets break the math and programming:
In math:
A = A + B + C
is same as
A = A + (B + C)
Now comes the programming part:
A = A + <something>
is the same as
A += <something>
this we can have
<something> = B + C
and when combined
A += B + C