Friday, November 20, 2009

Short Hand Assignment Operator in C++


Short Hand Assignment Operator in C++ Programming

Short hand assignemnt operators are also known as compound assignment operator. The advantage of using short hand assignment operator is that it requires less typing and hence provides efficiency.

A C++ Program example without using short hand assignment operator.


#include <iostream>

int main ()
{

    using std::cout;
    using std::endl;

    int a = 3;
    cout << "Value of a is : "<< a << endl;

    a = a + 1;
    cout << "Value of a is : "<< a << endl;

    a = a - 1;
    cout << "Value of a is : "<< a << endl;

    a = a * 2;
    cout << "Value of a is : " << a << endl;

    a = a / 2;
    cout << "Value of a is : " << a << endl;

    a = a % 2;
    cout << "Value of a is : " << a << endl;

    return 0;
}


A C++ Program example that uses short hand assignment operator


#include <iostream>

int main ()
{

    using std::cout;
    using std::endl;

    int a = 3;
    cout << "Value of a is : " << a << endl;

    a += 1;
    cout << "Value of a is : " << a << endl;

    a -= 1;
    cout << "Value of a is : " << a << endl;

    a *= 2;
    cout << "Value of a is : " << a << endl;

    a /= 2;
    cout << "Value of a is : " << a << endl;

    a %= 2;
    cout << "Value of a is : " << a << endl;

    return 0;
}


Note :

From the above two example it is clear that statement
a = a + 1 is same as a += 1 and
a = a - 1 is same as a -= 1 and
a = a * 1 is same as a *= 1 and
a = a / 1 is same as a /= 1 and
a = a % 1 is same as a %= 1

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.
Want to learn more? View List Of All Chapters

6 comments:

  1. When it's written a+1=a,then
    if the value of a is assigned 10 then during execution would it not take the value of 10 both in the L.H.S and R.H.S?

    could you plz help me out?

    ReplyDelete
  2. no, 1st it will execute the LHS & then save the value in RHS "a"

    ReplyDelete
  3. what is the advantage in using a shorthand operator ????

    ReplyDelete
  4. These blogs are valuable because these are providing such informative information for all the people.
    c++ programming tutorial

    ReplyDelete