Assignment Statements
-
Syntax of assignment statements:
Variable_Name = Expression;
-
Example:
double velocity, time, distance; // Variable declarations
velocity = 15.7; // Assigns the value of 15.7 to the variable "velocity"
time = 2.98; // Assigns the value of 2.98 to the variable "time"
distance = velocity * time; // Assigns the product of "velocity"
and "time" to the variable "velocity"
-
In computer programming, you should not think of the operator = as the equal sign
that is commonly used in mathematics. You must think of it as the assignment operator
which assigns the value of the expression on the right-hand side
to the variable on the left.
-
The expression on the right is first evaluated and then its value is assigned to the variable on the left.
-
Therefore the following statement is totally valid if the variable
count has been declared an integer and has an integer value assigned to it:
count = count + 5;
This statement causes the integer that was stored in count
to be increased by 5, and the resulting integer is then stored in count
replacing the original value.
However, if you read the = sign as the mathematical equal sign, then the statement is a meaningless equation,
since no number can have a value 5 more than itself, i.e. the equation has no solution at all.
-
We will encounter many other operators later. The entities operated on by an operator are called its operands.
-
There are 3 types of operators in C++. The unary, binary and ternary operators have one, two and three operands respectively.