Compound Assignment Operators in C programming
Understanding Compound Assignment Operators in C
Compound assignment operators in C are shorthand operators that combine an arithmetic operation with an assignment. They allow you to perform an operation on a variable and then assign the result back to that variable in a single step.
List of Compound Assignment Operators
Here are the compound assignment operators available in C:
+=
: Adds and assigns-=
: Subtracts and assigns*=
: Multiplies and assigns/=
: Divides and assigns%=
: Modulus and assigns&=
: Bitwise AND and assigns|=
: Bitwise OR and assigns^=
: Bitwise XOR and assigns<<>=
: Bitwise left shift and assigns>>=
: Bitwise right shift and assigns
How to Use Compound Assignment Operators
Compound assignment operators are used to simplify code and make it more readable. Instead of writing a full expression with both an operation and an assignment, you can use these shorthand operators.
Examples
Using +=
Operator
Adds the right operand to the left operand and assigns the result to the left operand:
#include <stdio.h>
int main() {
int a = 10;
a += 5; // Equivalent to a = a + 5;
printf("a = %d\n", a); // Output: a = 15
return 0;
}
Using *=
Operator
Multiplies the left operand by the right operand and assigns the result to the left operand:
#include <stdio.h>
int main() {
int b = 6;
b *= 4; // Equivalent to b = b * 4;
printf("b = %d\n", b); // Output: b = 24
return 0;
}
Using &=
Operator
Performs a bitwise AND operation on the left and right operands and assigns the result to the left operand:
#include <stdio.h>
int main() {
int x = 14; // Binary: 1110
x &= 7; // Binary: 0111
printf("x = %d\n", x); // Output: x = 6 (Binary: 0110)
return 0;
}
Why Use Compound Assignment Operators?
Using compound assignment operators can make your code more concise and readable. They help reduce redundancy and make it easier to understand the intention behind the operations performed on variables.
Comments
Post a Comment