What are Variables in C++?

A variable is a symbolic name for a memory location in which data can be stored and subsequently recalled. Variables are used for holding data values so that they can be utilized in various computations in a program. All variables have two important attributes:

A type which is established when the variable is defined (e.g., integer, real, character). Once defined, the type of a C++ variable cannot be changed.

A value which can be changed by assigning a new value to the variable. The kind of values a variable can assume depends on its type. For example, an integer variable can only take integer values (e.g., 2, 100, -12). A variable is used for the quantities which are manipulated by a computer program. For example a program that reads a series of numbers and sums them will have to have a variable to represent each number as it is entered and a variable to represent the sum of the numbers.

Let us illustrate the uses of some simple variable.

#include <iostream.h>
          int main (void)
          {
int workDays;
float workHours, payRate, weeklyPay; workDays = 5;
workHours = 7.5;
payRate = 38.55;
weeklyPay = workDays * workHours * payRate; cout << "Weekly Pay = ";
cout << weeklyPay;
cout << '\n';
}

The above given program calculates the weekly pay using three variables workDays, workHours, and payRate. In order to distinguish between different variables, they must be given identifiers. Each variable needs an identifier that distinguishes it from the others, for example, in the previous code the variable identifiers were weeklyPay, workDays, workHours and payRate, but we could have called the variables any names we wanted to invent, as long as they were valid identifiers.

Leave a Comment

Your email address will not be published. Required fields are marked *