Values and variables in a C++ Program:-


Variables aren’t much use if a programmer can’t give them values. Variables are assigned values in an assignment statement. The general form of such a statement is:

<identifier> = <value>;

The left-hand side of the = sign is the name of the variable that we want to assign a value to and the right-hand side is the value. The effect is that the value of the variable whose identifier is on the left becomes equal to the value that is on the right. For example:

// Declarations
int grade;
char answer;
string name;

// Assignments
grade = 70;
answer = 'a';
name = "alan turing";

These three statements assign the three values on the right to the variables named on the left. In each case the variable has to have the same type as the value assigned to it; it doesn’t make sense to assign a string value to an integer variable. As examples of what cannot be done, assuming the types in the declarations above, these assignments are not allowed:

grade = "a*"; // cannot assign string to int
name = 100; // cannot assign int to string
answer = "hello"; // cannot assign string to char

Unlike the algebraic use of =, it is not possible to write assignment statements with the variable’s identifier on the right. This is not allowed and will cause a compilation error:

'a' = grade; // Not allowed!

To make sure that you remember this, remember to get into the habit of reading the = sign in an assignment statement as “is assigned” or “becomes equal to”.

In all the correct assignment statements so far the right-hand side of the assignment has been a simple value, called a literal value. It is probably more common for it to be an expression. An expression is something that calculates a new value. For example:

grade = 70 + 2; // grade is 72
name = "ada " + "lovelace"; // name is "ada lovelace"

These expressions can also contain variables:

int sheep;
int pigs;
int animals;

sheep = 50;
pigs = 100;

animals = sheep + pigs; // animals is assigned 150

Finally, the variable that appears on the left-hand side can also appear on the right-hand side:

int sheep;

sheep = 50;

sheep = sheep + 1; // sheep is now 51

The important thing to remember, especially when the same variable appears on both sides of the assignment statement, is that the value of the expression on the right is calculated first and the result is then assigned to the value of the variable named on the left. This means that a statement such as:

aNumber = aNumber + 1;

has the effect of adding one (called incrementing) to the value of aNumber. The right-hand side is calculated first, and the result is then assigned to aNumber.