GET EDUCATE

Contents
Basics of C Programming

⯈Basic C Programs

Assignment operator in C

  • The operator for assignment is ‘=’.
  • The other operators that we can use is +=, -=, *=, /=. %=, >>=, <<=, &=, ^=, |= (This is also called as shorthand notation)
  • The general form is. 
    • LHS = RHS;
    • Evaluate the RHS first and store the answer in the LHS variable.
    • There cannot be any constant on the LHS of assignment.
      • 4 = x is an error, it says store x in 4, which is mathematical error, we cannot update the value of constants.
    • There cannot be any expressions on the LHS of assignment.
      • a+b = c is an error, it says store c in a+b.
    • There should be only one variable on the LHS of assignment.

Examples:

  • a = 4, it says store the value of a in 4.
  • a = b+c, store the value of b+c in a.

Multiple Assignment

We can initialize multiple values using the assignment operator.

a = b = c = 10;

In the above expression we have three assignment operators. The assignment operator has the associativity from RHS to LHS. Therefore we first execute c = 10. The value 10 is stored in ‘c’.

The next statement that gets executed is b = c, store the value c in b. Therefore b = 10.

The next statement that gets executed is a = b, store the value b in a. Therefore a = 10.

The following expression is invalid,

a = b = 4 = c;

Since, there is a constant on the LHS of the assignment operator.

Short-hand notation in C

If we have the expression as,

  • a = a + b, then we can write it as, a+=b;
  • a = a * b, can be written as a*=b;
  • a = a>>b, can be written as a>>=b;

if a = 4, b = 5 and c = 6, then

a = a * b + c is NOT same as a*=b+c

a = a * b + c, says evaluate RHS first and store the answer in LHS.

a = 4 * 5 + 6 = 26

But,

a * = b+c, says evaluate b+c first, then multiply the answer with ‘a’

a * = 5 +6

a * = 11

a = 4 * 11 = 44 

Scroll to Top