C Programming Tutorial – Assignment Operators

The assignment operators assign values to variables. Once values are assigned the variables are evaluated in expressions and return a single value.

There are three types of assignments as shown below.

1. Variable = Value( e.g., a = 4)
2. Variable = Expression( e.g., a = 3 + b)
3. Variable = Variable <Operator> Value (e.g., a = a + 3 or a += 3)

You can see from the above examples, that there is a left value(L-value) and (R-value). This assignment has a right to left associativity. In other words, right value(L-value) must be unambiguous or known, otherwise assignment will not work.

Precedence of operator

Every operator has a precedence in operators hierarchy, and it is executed in that order in an expression. The assignment operators have the least preference, so it executed last.

How many types of assignment operators

Let’s see how many assignment operators available to us.

Example Program:

OperatorExampleAssociativity
=A = 10 or B = CRight to Left
+=A += 10Right to Left
-=A -= 100Right to Left
/=A /= 12Right to Left
*=A *= 10Right to Left
%=A %= 5Right to Left
&=A &= 10Right to Left
|=A |= 10Right to Left
^=A ^= 4Right to Left
>>=A >>= 4Right to Left
<<=A <<= 3Right to Left

Example Program

This is an example program to demonstrate the effect of each assignment operator. You can run this program in any standard C compiler and it will work.

#include  <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main()
{

    int a,b,c,d;

/* simple assignment */

    a = 1000;
    b = 400;
    c = 120;

    printf("\n\n\n\n\n");
    printf("\t\t\ta:=%d\n",a);
    printf("\t\t\tb:=%d\n",b);
    printf("\t\t\tc:=%d\n",c);

/* assignment with arithmetic operators */

    a += b;
    b -= c;

    printf("\t\t\ta += b:=%d\n",a);
    printf("\t\t\tb -= c:=%d\n",b);

    a *= b;
    b /= c;

    printf("\t\t\ta *= b:=%d\n",a);
    printf("\t\t\tb /= c:=%d\n",b);

    a %= b;
    b ^= c;

    printf("\t\t\ta MOD= b:=%d\n",a);
    printf("\t\t\tb ^= c:=%d\n",b);

    a |= b;
    b &= c;

    printf("\t\t\ta |= b:=%d\n",a);
    printf("\t\t\tb &= c:=%d\n",b);

    a >>= 1;
    b <<= 2; printf("\t\t\ta >>= b:=%d\n",a);
    printf("\t\t\tb <<= c:=%d\n",b);

    getch();
    return 0;

}

Output – C Assignment Operators

The output of the above program is given below. Throughout the program, the value of variables a, b and c changes several times.

Output - C Assignment Operators Program

Output – C Assignment Operators Program


Bibliography

Balagurusamy, E. 2000. Programming in ANSI C. Tata McGraw-Hill Education,.

Brian W. Kernighan, Dennis M. Ritchie. 1988. C Programming Language, 2nd Edition. Prentice Hall.

Kanetkar, Yashavant. 20 November 2002. Let us C. Bpb Publications.