a = b + 1;
In above C statement we are adding 1 to value of b and storing it in a.
In C there are two kinds of value
- R-value - Read Value e.g. Value stored in variable, constant value.
- L-value - Location Value (Address) e.g Address of variable.
Hence R-value from Right hand side of = are evaluated and stored in the L-value left hand side. Sometimes people say R-value as right value and L-value as left value. Right hand side part of = can contain variables and constants while the left hand side should be always variable.
There are other short hand assignment operators.
- Add assignment (+=) e.g. a += b; which is equivalent to a = a + b
- Subtract assignment (-=) e.g. a -= b; which is equivalent to a = a - b
- Multiply assignment (*=)
- Division assignment (/=)
- Remainder assignment (%=)
- Bit-wise and assignment (&=)
- Bit-wise or assignment (|=)
- Bit-wise xor assignment(^=)
- Bit-wise left shift assignment (<<=)
- Bit-wise right shift assignment (>>=)
Following example shows the usage of the above assignment operators.
#include <stdio.h> int main() { int a; int b = 1; a = b + 5; b += 2; printf("Value of a is %d\n", a); printf("Value of b is %d\n", b); return 0; }
output of above program is
Value of a is 6 Value of b is 3
Can we mix data types on right hand side ? Yes, and it is already discussed when discussing operators.
Can we mix data types in = operator ? There are two possibility which is shown in below program first and then explained.
#include <stdio.h> int main() { int a = 1; float b = 2.3f; a = b + 1; b = a - 10; printf("Value of a is %d\n", a); printf("Value of b is %f\n", b); return 0; }
output of above program is
Value of a is 3 Value of b is -7.000000
In following expression -
- a = b + 1;
- first b + 1; is evaluated, since b is float and 1 is int, 1 is promoted to float and addition is carried which results in 3.3.
- then 3.3 is assigned to a which is integer, then approximation is done and only 3 is stored.
- b = a - 10;
- first a - 10 is evaluated, since a and 10 are integer hence no data type upgradation.
- During assignment -7 is upgraded to float and stored in b.
Links
Quiz - Not Yet written !!Next Article - C Programming #13: Operators - Increment, Decrement
Previous Article - C Programming #11: Operators - Conditional
All Article - C Programming
No comments :
Post a Comment