Topic 2: Variables and Constants

Variables

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.

Memory location example
Figure 2.1

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:
dataType variableName [= initialValue];

Example 1: Declare a variable of type integer with the name num
    1. int num;

Example 2: Declaration and initialization
  • 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.

Memory data example
Figure 2.2

Data Types

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:

  • Built-in (primitive type): Part of the compiler
  • Class: Created by the programmer

Variables and Named Constants

There are two types of memory locations that can be declared:

  1. Variables are memory locations whose values can change during runtime. The initial value is optional but recommended. If a variable is not initialized, it contains the previous value of that memory location, which may be the wrong type (called a garbage value).
  2. Named Constants are memory locations whose values cannot change during program execution. They should be initialized with the value they will hold for the duration of the program. The const keyword indicates that the memory location is a named constant. The initialization is mandatory.
Example: Declare named constants
    1. const double PI = 3.14;
    2. const double MIN_HEIGHT = 100.5;
    3. const bool PAID = true;
    4. const char NO = 'N';
    5. const string COMPANY_NAME = "XYZ Company Ltd";

Advantages of using constants:

  • Makes the program more self-documenting (meaningful words in place of numbers)
  • Value cannot be inadvertently changed during runtime
  • Typing a name is less error-prone than a long number
  • Mistyping a constant’s name will trigger a compiler error; mistyping a number will not
  • If the constant needs to be changed, it only needs to be changed in one place

Literal 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:

  1. Literal Constants
    • Literal constants are fixed values that are directly written in the code at the point where they are used.
    • They are also known as literal values or literals.
    • Examples of literal constants include numbers like 5, 3.14, characters like 'A', strings like "Hello, world!", and boolean values like true or false.
    • Literal constants are directly substituted into the code wherever they are used, and their values are not expected to change during the execution of the program.
  2. Named Constants
    • Named constants are fixed values that are given a symbolic name or identifier in the code.
    • They are defined using a constant declaration statement in the program.
    • Once a named constant is defined, its value cannot be changed during the execution of the program.
    • Named constants are typically used to improve code readability, maintainability, and to avoid magic numbers in the code.
    • By using named constants, if the value needs to be changed, it can be done in a single place in the code where the constant is defined, making it easier to update and maintain.

Selecting a Data Type

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 characters
Data type storage size and range
Figure 2.3: Storage size and range for signed and unsigned data types

Variable Names

The name chosen for a variable should be short and descriptive. This helps in writing concise and understandable code.

Rules for Naming Variables in C++

  • Name can only begin with a letter or an underscore (_)
  • Can contain only letters, numbers, and underscores. No punctuation marks, spaces, or other special characters (such as $ or %) are allowed
  • Cannot be a keyword (a word that has special meaning in C++)
  • Names are case-sensitive. Example: discount is different from DISCOUNT and Discount

Good Programming Practices for Naming Variables

  • Use uppercase letters for named constants and lowercase for variables
  • Separate words in constants with underscores
  • Use camel case for variables containing multiple words
Table 2.1: Examples of valid C++ variable names
Variable names
total interest grossPay
slope computePay density
findMin count cha
Table 2.2: Examples of invalid C++ variable names
variable names Reason
2AB3 Begins with a number
E-6 Contains a special character
for This is a keyword

Practice Questions

  1. What is a variable?
  2. What is the purpose of the const keyword in C++?
  3. What are the advantages of using constants in a program? List at least three.
  4. Identify the errors in the following variable declarations and correct them:
    int 2ndValue;
    float rate-of-increase;
    double PI = 3.14159;
  5. Explain the difference between the float and double data types in C++.
  6. Declare a variable of type double with the name area and initialize it to 50.5.
  7. Declare a constant integer with the name MAX_USERS and initialize it to 1000.
  1. Create a program that calculates the area of a rectangle using the values 4 and 6 for the length and width respectively.
  2. Declare a 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.
  3. A program that calculates simple interest based on Principal ($100.00), Rate (2%), Time (5 years). The formula is: (principal * rate * time) / 100.
Coming Soon...