Statements in a function -calculations

i am studying the basics, i'm at Functions II

The following is given here. ( my question is after.)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20


#include <iostream>
using namespace std;

void duplicate (int& a, int& b, int& c)
{
  a*=2;
  b*=2;
  c*=2;
}

int main ()
{
  int x=1, y=3, z=7;
  duplicate (x, y, z);
  cout << "x=" << x << ", y=" << y << ", z=" << z;
  return 0;
}


the output is

x=2, y=6, z=14



but how did the following double the numbers?
{
a*=2;
b*=2;
c*=2;
}


was that some type of math i missed in H.S?
hopefully it was a lesson of c++ i missed.

by the way i understand the entire lesson accept for that one peice.

here is where the totorial is located:
http://www.cplusplus.com/doc/tutorial/functions2.html

any help is much appreciated.


a*=x
is the same as
a = a * x

so a*=2 is the same as a = a *2.

so it takes the original value of a, multiplies is by two, and sticks it back into the value of a.

hope this helps.
It's generally a C (not C++) syntax of "operate and assign back" (as I call it) operator.

1
2
3
4
a += 2;
b -= 2;
c *= 2;
d /= 2;


are equivalently the same as

1
2
3
4
a = a + 2;
b = b - 2;
c = c * 2;
d = d / 2;


But you need to note that operators in C++ can be overloaded. The equivalences I mentioned above is applicable for primitive data types. If the variables are objects it may or may not mean the same thing.
GOT IT. Easy to remember.

Thank you all very much.
Topic archived. No new replies allowed.