In the previous unit, we have seen that variables are basically memory locations and they can hold certain values. But, how to assign values to the variables? C provides an assignment operator for this purpose. The function of this operator is to assign the values or values in variables on right hand side of an expression to variables on the left hand side.
The syntax of the assignment expression is as follows:
Variable = constant / variable/ expression;
The data type of the variable on left hand side should match the data type of constant/variable/expression on right hand side with a few exceptions where automatic type conversions are possible. Some examples of assignment statements are as follows:
b = a ; /* b is assigned the value of a */
b = 5 ; /* b is assigned the value 5*/
b = a+5; /* b is assigned the value of expr a+5 */
The expression on the right hand side of the assignment statement can be:
The above mentioned expressions are different in terms of the type of operators connecting the variables and constants on the right hand side of the variable. Arithmetic operators, relational operators and logical operators are discussed in the following sections.
For example,
int a;
float b, c, avg, t;
avg = (b + c) / 2; /* arithmetic expression */
a = b && c; /* logical expression */
a = (b + c) && (b < c); /* mixed expression */