C assignment operator



Assignment Operator in C Programming Language :

  1. Assignment Operator is Used to assign value to an variable.
  2. Assignment Operator is denoted by equal to sign
  3. Assignment Operator is binary operator which operates on two operands.
  4. Assignment Operator have Two Values – L-Value and R-Value.Operator copies R-Value into L-Value.
  5. Assignment Operator have lower precedence than all available operators but has higher precedence than comma Operator.

Pictorial Representation :
Assignment Operator in C Programming

Recommanded Reading : Operator Precedence Table | comma operator

Different Ways of Using Assignment Operator :

Way 1 : Assignment Operator used to Assign Value

int main() {
   int value;
   value = 55;
   return (0);
}

In the above example, we have assigned 55 to a variable ‘value’.

Way 2 : Assignment Operator used To Type Cast.

int value;
value = 55.450;
printf("%d",value);

Assignment operator can type cast higher values to lower values. It can also cast lower values to higher values

Way 3 : Assignment Operator in If Statement

if(value = 10)
  printf("True");
else
  printf("False");

It would be interesting to understand above program. Above Program will always execute True Condition because Assignment Operator is used inside if statement not comparison operator. Lets see what will happen in above example –

Constant number 10 will be assigned to variable ‘value’. Variable ‘value’ will be treated as positive non-zero number, which is considered as true condition.

if(value = 0)
  printf("True");
else
  printf("False");

In below case else block will be executed

Shorthand assignment operator

Shorthand assignment operator is used express the syntax that are already available in shorter way

Operator symbolName of the operatorExampleEquivalent construct
+=Addition assignmentx += 4;x = x + 4;
-=Subtraction assignmentx -= 4;x = x – 4;
*=Multiplication assignmentx *= 4;x = x * 4;
/=Division assignmentx /= 4;x = x / 4;
%=Remainder assignmentx %= 4;x = x % 4;

Example : Shorthand assignment operator

#include<stdio.h>

int main() {

   int res;

   res = 11;
   res += 4;
   printf("\nResult of Ex1 = %d", res);

   res = 11;
   res -= 4;
   printf("\nResult of Ex2 = %d", res);

   res = 11;
   res *= 4;
   printf("\nResult of Ex3 = %d", res);

   res = 11;
   res /= 4;
   printf("\nResult of Ex4 = %d", res);

   res = 11;
   res %= 4;
   printf("\nResult of Ex5 = %d", res);

   return 0;
}

Output :

Result of Ex1 = 15
Result of Ex2 = 7
Result of Ex3 = 44
Result of Ex4 = 2
Result of Ex5 = 3