Assignment Operator

Assignment Operator

Published by: Nuru

Published date: 21 Jun 2021

Assignment Operator Photo

Assignment Operator

Assignment Operator can be learned by the following points:

  • It is the equal sign (=). Its use in programming is somewhat different from its use in regular maths.
  • It is used to assign the result of an expression to the variable.
  • If we write x = y; in a C program, it doesn't mean "x is equal to y." Instead, it means "assign the value of y to x."
  • In a C statement, the right side can be any expression, and the left side must be a variable name. Thus,the form is as follows:

variable=expression

  • When executed, the expression is evaluated, and the resulting value is assigned to the variable.
  • x= x+2; assigns value evaluated by expression x+2 to variable itself.
  • In addition, C has a set of shorthand operators of the form:

v op=exp;

/* Here v is a variable, exp is an expression and op is a C binary arithmetic operator. The operator op= is called shorthand assignment operator. */

  • The assignment statement

v op=exp;

is equivalent to

v = v(op) Exp;

 

Statement with simple assignment operator Statement with simple shorthand operator
a = a+1 a+ = 1
a = a-1 a- = 1
a = a *(n+1) a* = (n+1)
a = a /(n+1) a/ = (n+1)
a = a%b a% = b

Compound Assignment Operators

  • It provides a shorthand method for combining a binary arithmetic operation with an assignment operation.
  • For example, if we want to increase the value of x by 5, or, in other words, add 5 to x and assign the result to x. we can write

x=x+5;

  • Using a compound assignment operator, which we can think of as a shorthand method of assignment, we can write x += 5;
  • In more general notation, the compound assignment operators have the following syntax (where op represents a binary operator):

exp1 op= exp2     This is equivalent to writing

    exp1 = exp1 op exp2