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

Check out this stream