C++ Assignment Operators

  • Assignment Operator (=)

Assignment operators are used to assign values to variables. In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

Example

int x=10;

Try it yourself! 


Operator Expression Equivalent to... Try it
= x=5; x=5; Try it

For example, let's have a look at the following code - I have included the evolution of the content stored in the variables as comments:

// assignment operator
#include <iostream>
using namespace std;
int main ()
{
  int a, b;         // a:?,  b:?
  a = 10;           // a:10, b:?
  b = 4;            // a:10, b:4
  a = b;            // a:4,  b:4
  b = 7;            // a:4,  b:7

  cout << "a:"<<a<<"\n";
  cout << "b:"<<b;
}

Try it


  • Compound Assignment Operator (+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=)

Compound assignment operators modify the current value of a variable by performing an operation on it. They are equivalent to assigning the result of an operation to the first operand:

A list of all compound assignment operators

Operator Expression Equivalent to... Try it
+= x+=3; x=x+3; Try it
-= x-=3; x=x-3; Try it
*= x*=3; x=x*3; Try it
/= x/=3; x=x/3; Try it
%= x%=3; x=x%3; Try it
&= x&=3; x=x&3; Try it
|= x|=3; x=x|3; Try it
^= x^=3; x=x^3; Try it
>>= x>>=3; x=x>>3; Try it
<<= x<<=3; x=x<<3; Try it

and the same for all other compound assignment operators. For example:

// compound assignment operators
#include <iostream>
using namespace std;

int main ()
{
  int a, b=3;
  a = b;
  a+=2;             // equivalent to a=a+2
  cout << a;
}

Comments

Popular posts from this blog

ភាសាកម្មវិធី C++៖ អថេរ ឬអញ្ញាតិ