C++ Assignment Operators

In C++, assignment operators allow variables to store and update values efficiently. These operators assign values directly or perform operations before assignment.

Tutorials dojo strip



Basic Assignment (=)

The simplest assignment operator is =, which stores a value in a variable.

Example

#include <iostream>
using namespace std;

int main() {
    int engineCC = 1000;  // Assigning a value
    cout << "Engine capacity: " << engineCC << " cc";

    return 0;
}




Using Compound Assignment Operators

Assignment operators can modify variables while assigning a value.

Example

#include <iostream>
using namespace std;

int main() {
    int torque = 80;  // Initial value

    torque += 20;  // Adds 20 to torque (80 + 20 = 100)
    
    cout << "Updated torque: " << torque << " Nm";

    return 0;
}

This shorthand makes the code cleaner, eliminating the need for torque = torque + 20;.




Common Assignment Operators

OperatorExampleEquivalent Expression
=power = 100;power = 100;
+=power += 50;power = power + 50;
-=power -= 30;power = power - 30;
*=power *= 2;power = power * 2;
/=power /= 4;power = power / 4;
%=power %= 3;power = power % 3;




Bitwise Assignment Operators

OperatorExampleEquivalent Expression
&=x &= 3;x = x & 3;
|=x |= 3;x = x | 3;
^=x ^= 3;x = x ^ 3;
>>=x >>= 3;x = x >> 3;
<<=x <<= 3;x = x << 3;

Tutorials dojo strip
Scroll to Top