Variables are memory locations used to store values. They can be visualized as storage bins as shown in Figure 2.1. Each memory location has a unique memory address and can store one item at a time. Before a memory space can be used, it needs to be reserved.
Variable declaration is reserving a memory location for storing values. It is done by writing a statement containing a data type, name of the variable, and (optional) initial value. The name allows the programmer to refer to the memory location later in the program using a descriptive word, instead of the memory address.
Syntax:num
- int num;
int count;
count = 0;
Note: The above two lines of code can be combined into one:
int count = 0;
When the above two examples are compiled, the data stored in memory is depicted in Figure 2.2.
The data type indicates what type of values a memory location will store (e.g., number, text, or address of another variable).
Two fundamental data type groups are:
There are two types of memory locations that can be declared:
const
keyword indicates that the memory location is a named constant.
The initialization is mandatory.
- const double PI = 3.14;
- const double MIN_HEIGHT = 100.5;
- const bool PAID = true;
const char NO = 'N';
Advantages of using constants:
Literal constants and named constants are both used in programming to represent fixed values that do not change during the execution of a program. However, they differ in how they are defined and used:
Selecting an appropriate data type for a memory location is crucial for efficient memory usage and accurate data representation. Here are some common data types:
bool
- stores Boolean values (true and false)short
and int
- store integers (numbers without a decimal place)float
and double
- store real numbers (numbers with a decimal place)
char
- stores characters (letters, symbols, or numbers not used in calculations)
string
- stores a sequence of charactersThe name chosen for a variable should be short and descriptive. This helps in writing concise and understandable code.
Variable names | ||
---|---|---|
total | interest | grossPay |
slope | computePay | density |
findMin | count | cha |
variable names | Reason |
---|---|
2AB3 | Begins with a number |
E-6 | Contains a special character |
for | This is a keyword |
const
keyword in C++?
int 2ndValue;
float rate-of-increase;
double PI = 3.14159;
float
and double
data types in C++.
double
with the name area
and initialize it to 50.5.
MAX_USERS
and initialize
it to 1000.const
variable for the value of π. Declare a variable for
the radius of the circle and initialise it to 3.5. Calculate and display the
circumference using the
formula: Circumference = 2 * π * radius.