C++ Variables (Identifiers) and Constants

Variable Names

Variables, also referred to as "identifiers" are named memory locations that have a type, such as an integer or character, and consequently, a size, which is inherited from their type. Since variables are types, they have a set of operations that can be used to change or manipulate them.

An identifier name can be made up of only the following:

Identifiers must begin with a letter or an underscore. However, some identifiers beginning with an underscore have special meanings, so generally user-defined identifiers begin with a letter.

There are some reserved words in C++, so the programmer should be cautious in his choice of identifier names. For example, "int" is a poor choice, since that is a reserved word indicating the type of the variable.

Variable Types

Refer to any text for a complete set of variable types. Here is a short list of commonly used types.

char A 1 byte integer usually used to store a character.
short A 2 byte integer.
int A 4 byte integer.
long 4 or 8 byte integer (compiler dependent).
float Single precision floating point number.
(7 digits or more - compiler dependent)
double Double precision floating point number.
(15 digits or more - compiler dependent)
bool Boolean literal. Values are true (numerically=1) or false (numerically=0).
string A variable number of characters.
Note: string is actually a C++ class. In order to use this datatype, you need to add the statement:
#include <string>
to the start of your program.

Variable Arrays

Arrays are fixed-sized sequential collections of elements of the same type. We can refer to the elements in the array as the first element, second element, and so forth until we get to the last element. To set up an array, use this command: variable_type array_name[no_of_elements]; Notice the square brackets used for the subscripts. Use these also when you want to reference an array element.

To refer to an index (individual element) within the array, use array_name[index]. In C/C++, the index of the first element is zero (0), and the index of the last element is no_of_elements - 1.

The simplest example of a "one dimensional" array is a simple list such as a shopping list with one item per line.
e.g. General Format for declaring a one-dimensional array:    data_type    variable_name [ no_of_elements ]
Or, for a two-dimensional array:
   data_type    variable_name [ no_of_rows ][ no_of_columns ] A familiar example of a two dimensional array is what you see when you use a spreadsheet program. There are cells organized into a grid of rows and columns.
e.g. Declare an integer array of 2 rows, 3 columns: int Nums[2][3];
Often you will see a constant declared to hold the array size, and then this constant used in the array declaration.
i.e.
const R_size = 2;
const C_size = 3;
int Nums[R_size][C_size];

Array elements can also be initialized when the array is declared.

int Nums[2][3] =
    {
    {1, 2, 3},
    {4, 5, 6}
    };

Format for Referencing 2-Dimensional Arrays

When you reference a particular array element, use a number, constant, variable or expression in the brackets. Of course the values in the brackets must be within the defined limits of the array size.

Here is a sample program that uses a one-dimensional array. This short program computes the sum of all the values found within the array. Take note of the differences between this and the one written in Pascal.

#include <iostream>
using namespace std;
int main()
{
   int i, sum = 0;
   int numbers[5] = {3, 7, 2, 4, 5};  // defines the array and initializes a value to each 
                                      // element of the array
   for (i = 0; i < 5; i++)
         sum += numbers[i];
   cout << "sum = " << sum << endl;
}

When compiled, the program will print out: sum = 21

Variable Initialization

Each variable in your program nust be declared and initialized. There are two ways in which we can do this. We can declare our variables first, like this:

                                                                           
  char letter;                                                                  
  string first_name;
  int x;                                                                        
  long student_id;                                                              
  float payRate;                                                                
  double pi;                                                                    
  bool valid;                                                                   
  int Nums[2][3];

then initialize them later in the program as a separate statement.

                                                                           
  letter = 'A';                                                                 
  first_name = "Ada";
  x = 7;
  student_id = 200201202;
  payRate = 12.85;
  pi = 3.1415926536;                                                            
  valid = true;                                                                 
  Nums[0][0] = 1;
  Nums[0][1] = 2;
  Nums[0][2] = 3;
  Nums[1][0] = 4;
  Nums[1][1] = 5;
  Nums[1][2] = 6;

The other way is to initialize them at the same time as they are declared (in one statement).

                                                                           
  char letter = 'A';                                                            
  string first_name("Ada");
  int x = 7;                                                                    
  long student_id = 200201202;
  double pi = 3.1415926536;
  float payRate = 12.85;                                                        
  bool valid = true;                                                            
int Nums[2][3] =
    {
    {1, 2, 3},
    {4, 5, 6}
    };

Constants

We can also declare our initialized variable as a constant, by adding the type qualifier const before the definition. The general format for a const declaration is shown below:

const type variable-name = any value you like

Inside of a program, you will see constants written like this:

                                                                           
  const float payRate = 12.85;                      
  const double pi = 3.1415926536;                   

Type Casting

Sometimes you may have different variable types mixed together in one statement, for example integers and floats. This is fine, but be aware that C++ will have to perform type coercion to convert the values in order to perform arithmetic operations and/or to store the results of the operations. This is referred to as implicit (or automatic) conversion.

But the programmer can also force the conversion of datatypes by type casting a value. It is simple to do, just put the data type and parentheses around the value that you want to cast.

e.g.
	int_value = int( float_value / 2 );

This page has been accessed     times.
Last modified: Friday, 21-Aug-2020 15:28:13 CST
Copyright 2000 Department of Computer Science, University of Regina.


 CS Dept Home Page

Teaching Material