Jun 15, 2014

C Programming #12: Operators - Assignment

Following article will discuss the assignment operators in C. Previously when discussing logical operators i mentioned that == is equality operator while = is assignment operator. Assignment operator is used to change the value of a variable. Simplest usage of assignment operator is


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
  1. R-value - Read Value e.g. Value stored in variable, constant value.
  2. 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.
  1. Add assignment (+=) e.g. a += b; which is equivalent to  a = a + b
  2. Subtract assignment (-=) e.g. a -= b; which is equivalent to a = a - b
  3. Multiply assignment (*=)
  4. Division assignment (/=)
  5. Remainder assignment (%=)
  6. Bit-wise and assignment (&=)
  7. Bit-wise or assignment (|=)
  8. Bit-wise xor assignment(^=)
  9. Bit-wise left shift assignment (<<=)
  10. Bit-wise right shift assignment (>>=)
NOTE : Logical operators do not have this shortcut assignments.

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