What is assignment?
Earlier, we learnt about all the data types, how to declare the variables using appropriate data types and their possible values of each data type. When we set the value to a variable first time, it is called initialization, and when we change the value using = operator, it's called an assignment.
int a; // Declaring a variable
int a = 5; // Declaring and initialization
a = 8; // assigning the values
What are the assignment operators?
Assignment operators are those operators, which perform operation on the variable and also assign the result to the variable same time. Following is the chart of all assignment operators. Earlier, we learnt about two unary operators - increment (++) and decrement (--) operators, they are assignment operators too.
Suppose, x = 15 and y = 6, then:
Suppose, x = 15 and y = 6, then:
Operator | Code | Operation | Result |
---|---|---|---|
= | x = y | x = y | x = 6 |
+= | x += y | x = x + y | x = 21 |
-= | x -= y | x = x - y | x = 9 |
*= | x *= y | x = x * y | x = 90 |
/= | x /= y | x = x / y | x = 2 |
%= | x %= y | x = x % y | x = 3 |
++ | x++ | x = x + 1 | x = 16 |
-- | x-- | x = x - 1 | x = 14 |
Suppose, x = true and y = false, then:
Operator | Code | Operation | Result |
---|---|---|---|
&= | x &= y | x = x & y | x = false |
|= | x |= y | x = x | y | x = true |
^= | x ^= y | x = x ^ y | x = true |
NOTE: These assignment operators are also called compound assignment operators and they are very efficient. So, these operators are used frequently.
No comments:
Post a Comment