Thread: can someone explain why this is? (very basic c++)

  1. #1
    Registered User
    Join Date
    Jul 2008

    can someone explain why this is? (very basic c++)

    // passing parameters by reference
    #include <iostream>
    using namespace std;
    void duplicate (int& a, int& b, int& c)
    int main ()
      int x=1, y=3, z=7;
      duplicate (x, y, z);
      cout << "x=" << x << ", y=" << y << ", z=" << z;
      return 0;
    my confusion comes when you get to a*=2;. I know what the code does when you compile it, but im afraid i dont understand exactly why its written like that. it has me very confused.

    basically what it looks like to me is
    "a[int] times equals 2"
    which as you can see, dosent make a lick of sense.

    can someone break it down for me, and tell me why its written this way? the tutorials im reading dont explain what im asking. hopefully you understand what it is im asking.

    Thanks in advance!

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    a *= 2 is equivalent to a = a * 2. It's a shorthand notation to save some typing. Basically the idea is that you take a and multiple by 2 in this case and store the result back in a.

  3. #3
    Registered User
    Join Date
    Mar 2007
    As MacGyver said, same thing goes for a += 2 or a -= 2 and so on also.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    New Zealand
    The thing to note here is that *= is an operator in its own right. It is not the same as * = (that's with a space between them).

    a *= 2; reads as "a is multiplied by 2"
    a * = 2; reads as "a times is assigned 2" which makes no sense.
    a = a * 2; reads as "a is assigned a times 2" which makes sense.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 19
    Last Post: 04-12-2009, 08:37 AM
  2. basic question about global variables
    By radeberger in forum C++ Programming
    Replies: 0
    Last Post: 04-06-2009, 12:54 AM
  3. Basic windows programming
    By Remedy in forum C Programming
    Replies: 3
    Last Post: 04-22-2003, 11:04 PM
  4. Moving from Visual Basic to Visual C++
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 04-10-2002, 09:57 PM
  5. Can someone explain "extern" to me?
    By valar_king in forum C++ Programming
    Replies: 3
    Last Post: 09-16-2001, 12:22 AM