0

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;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Is score something other than a primitive type - like float, int, string, etc..? – joe.dinius Aug 20 '20 at 22:50
  • [Comma has interesting behaviour.](https://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator) The outcome of `score += var1, var2, var3` surprised me until I thought about precedence. – user4581301 Aug 20 '20 at 22:57

3 Answers3

4

You can simply do:

score += var1 + var2 + var3;
cigien
  • 57,834
  • 11
  • 73
  • 112
2

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

@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