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 (+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=)
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:
#include <iostream>
using namespace std;
int main ()
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
cout << a;
}
Comments
Post a Comment