C

Assignment Operators in C Programming

Assignment operators are used to assign values to variables. The most common operator is the simple assignment operator (=), but C also provides several compound assignment operators that perform an operation and an assignment in a single step.

1. Simple Assignment Operator (=)

The = operator assigns the value on the right side (R-value) to the variable on the left side (L-value).

  • Syntax: variable = expression;

  • Example: int x = 10; assigns the integer 10 to the variable x.

2. Compound Assignment Operators

These are shorthand operators that combine an arithmetic or bitwise operation with assignment.

OperatorDescriptionEquivalent Expression
+=Add and assignx = x + y
-=Subtract and assignx = x - y
*=Multiply and assignx = x * y
/=Divide and assignx = x / y
%=Modulus and assignx = x % y
<<=Left shift and assignx = x << y
>>=Right shift and assignx = x >> y
&=Bitwise AND and assignx = x & y
^=Bitwise XOR and assignx = x ^ y
`=`Bitwise OR and assign

3. Practical Code Example

The following program demonstrates how these operators function in a real C script:

Key Takeaways

  • L-Value Requirement: The left side of an assignment operator must be a variable (a memory location), not a constant (e.g., 10 = x; is an error).

  • Right-to-Left Associativity: Assignment operators are evaluated from right to left. For example, a = b = c = 50; assigns 50 to c, then c to b, and finally b to a.

  • Efficiency: Compound operators are not just shorter to write; in some older compilers, they could be slightly more efficient, though modern compilers optimize both forms equally.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now