C Assignment Operators

Summary: in this tutorial, you’ll learn about the C assignment operators and how to use them effectively.

Introduction to the C assignment operators

An assignment operator assigns the vale of the right-hand operand to the left-hand operand. The following example uses the assignment operator (=) to assign 1 to the counter variable:

#include <stdio.h> int main() { int counter; // assign 1 to counter counter = 1; printf("%d\n", counter); // 1 return 0; }
Code language: C++ (cpp)

After the assignmment, the counter variable holds the number 1.

The following example adds 1 to the counter and assign the result to the counter:

#include <stdio.h> int main() { int counter; // assign 1 to counter counter = 1; // add one to the counter counter = counter + 1; printf("%d\n", counter); return 0; }
Code language: C++ (cpp)

The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand.

Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.

The following example uses a compound-assignment operator (+=):

int x = 5; x += 10;
Code language: C++ (cpp)

The expression:

x += 10
Code language: C++ (cpp)

is equivalent to the following expression:

x = x + 10;
Code language: C++ (cpp)

The following table illustrates the compound-assignment operators in C:

OperatorOperation PerformedExampleEquivalent expression
*=Multiplication assignmentx *= yx = x * y
/=Division assignmentx /= yx = x / y
%=Remainder assignmentx %= yx = x % y
+=Addition assignmentx += yx = x + y
-=Subtraction assignmentx -= yx = x – y
<<=Left-shift assignmentx <<= yx = x <<=y
>>=Right-shift assignmentx >>=yx = x >>= y
&=Bitwise-AND assignmentx &= yx = x & y
^=Bitwise-exclusive-OR assignmentx ^= yx = x ^ y
|=Bitwise-inclusive-OR assignmentx |= yx = x | y

Summary

  • A simple assignment operator assigns the value of the left operand to the right operand.
  • A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.
Was this tutorial helpful ?