Assignment Operators
Here, we see the different ways in which a variable can be assigned values.
There are following assignment operators supported by C language:
Operators | What They Do .. | Meaning |
---|---|---|
= | Assigns values to variables. | a=b |
+= | Assigns a value incremented by some value. | a=a+b |
-= | Assigns a value decremented by some value. | a=a-b |
*= | Assigns a value multiplied by some value. | a=a*b |
/= | Assigns a value divided by some value. | a=a/b |
%= | Assigns a value got by taking by some value. | a=a%b |
<<= | Assigns a value got by shifting some bits to left. | a=a< |
>>= | Assigns a value got by shifting some bits to left. | a=a>>b |
&= | Performs the AND operation on corresponding bits of values. | a=a&b |
|= | Performs the OR operation on corresponding bits of values. | a=a|b |
^= | Performs the XOR operation on corresponding bits of values. | a=a^b |
Simple Assignment
There are two ways as shown :1. During declaration
2. Later in the program
Syntax for Simple Assignment:
[variable]=[variable\constant]
Example:
#include< stdio.h> int main() { int a=10,b; b=20; printf("Assignment During Declaration a=%d ",a); printf("\nAssignment After Declaration b=%d ",b); return 0; }
This will produce following output:
Assignment During Declaration a=10 Assignment After Declaration b=20
Compound Assignment Operators
AS SHOWN , these use a combination of assignment operator and either arithmetic or bitwise operators.
Syntax for Compound Assignment :
[variable][operators]=[variable\constant]
C Example
#include<stdio.h> int main() { int a=1,b=2,c=3,d=4,e=6,f=5; printf("\n a becomes %d , b becomes %d , c becomes %d ,d becomes %d ,e becomes %d , f becomes %d",a,b,c,d,e,f); a+=b; c-=b; d*=b; e/=b; f%=b; printf("\na becomes %d , b becomes %d , c becomes %d ,d becomes %d ,e becomes %d , f becomes %d",a,b,c,d,e,f); a&=b; c|=b; d^=b; e<<=b; f>>=b; printf("\na becomes %d , b becomes %d , c becomes %d ,d becomes %d ,e becomes %d , f becomes %d",a,b,c,d,e,f); return 0; }