Assignment Operators in C | Shorthand operators in C

Assignment Operators in C | Shorthand operators in C

Assignment/shorthand operators are used to update the value of a variable in an easy way. There are various assignment operators provided by C language.

  • =
  • +=
  • -=
  • *=
  • /=
  • %=
  • &=
  • |=
  • ^=
  • <<=
  • >>=

Operator

Description

= It is used to assign some value to a variable.

Example:

A=10

+= It is used to increment the value of a numeric variable by adding some value to the existing value.

Example:

A=10
A+=5  //A=A+5
A=15

-= It is used to decrement the existing value of a numeric variable by subtracting some value from the existing value.

Example:

A=10
A-=5  //A=A-5
A=5

*= It is used to multiply existing value of a numeric variable by another value and then store the result in it.

Example:

A=10
A*=5  A=A*5
A=50

/= It is used to divide the existing value of a numeric variable by another value and then store the result in

Example:

A=10
A/=5  //A=A/5
A=2

%= It is used to divide the existing value of a numeric variable by another value and then storing the remainder in it.

Example:

A=10
A%=5  //A=A%5
A=0

&= It is used to apply bitwise AND operator on existing value of a numeric variable by another value and then storing the result in it.

Example:

A=10
A&=7  //A=A&7
A=2

|= It is used to apply bitwise OR operator on existing value of a numeric variable by another value and then storing the result in it.

Example:

A=10
A|=7  //A=A|7
A=15

^= It is used to apply bitwise XOR operator on existing value of a numeric variable by another value and then storing the result in it.

Example:

A=10
A^=7  //A=A^7
A=13

<<= It is used to apply Bitwise LEFT SHIFT operator on existing value of a numeric variable by another value and then storing the result in it.

Example:

A=10
A<<=1  //A=A<<1
A=20

>>= It is used to apply Bitwise RIGHT SHIFT operator on existing value of a numeric variable by another value and then storing the result in it.

Example:

A=10
A>>=1  //A=A>>1
A=5

Example 1

Program to demonstrate  shorthand operators in C

#include<stdio.h>
int main()
{
int a=20;
a+=4;
printf("\na=%d",a); /*a=24*/
a-=13;
printf("\na=%d",a);  /*a=11*/
a*=6;
printf("\na=%d",a);  /*a=66*/
a/=5;
printf("\na=%d",a);  /*a=13*/
a%=5;
printf("\na=%d",a);  /*a=3*/
return(0);
}

 Example 2

Program to demonstrate  the use of shorthand operators in C.

#include<stdio.h>
int main()
{
int a=10;
a&=7;
printf("\na=%d",a);  /*a=2*/
a=10
a|=7;
printf("\na=%d",a);  /*a=15*/
a=10
a^=7;
printf("\na=%d",a); /*a=13*/
a=10
a<<=1;
printf("\na=%d",a);  /*a=20*/
a=10
a>>=1;
printf("\na=%d",a);  /*a=5*/
return(0);
}

 

Spread the love
Lesson tags: assignment operator programs, assignment operators in C, augmented operators in C, shorthand operators in C
Back to: C Programming Language
Spread the love