A variable is a named location in computer memory where a program can store and retrieve a value. The value of this variable can be changed one or more times during the execution of a program. 

Defining Variables

Before a variable can be used in a program it must be declared. This variable declaration will specify to the compiler the name and type of a variable. The size of the data type will vary depending on the computer platform. Any attempt to use a variable that hasn’t been declared will result in the compiler generating an error message. A variable declaration will consist of the variable type followed by the variable name. Multiple single-line variable declarations are possible by separating each declaration with a comma –

int x //declares variable of type int
float x,y,z; //declares variables of type float
short int x,y,z; //declares variables of type short int
unsigned int x,y,z; //declares variables of type unsigned int
char xyz; //declares variable of type char

Rules for Naming Variables in CPP

  • All variables must begin with a letter of the alphabet or underscore.
  • Although variable names can be alphanumeric, they cannot start with a number.
  • Uppercase characters are distinct from lowercase characters.
  • Variable names cannot be c++ reserved keywords.

Initialising Variables by Assigning Values

A variable can be assigned an initial value when it is created or assigned a value after creation but these values must be in the correct format. In C++, there are three ways to initialise a variable -

Using the assignment operator (=) –

int value=10; //creates and initialises variable value of type int 

Using parenthesis ()

int value (20) ; //creates and initialises variable value of type int to 20

Using braces {}

int value{30} ; //creates and initialises variable value of type int to 30

An uninitialised variable is a variable that is declared but will have some unknown value known as a “garbage value”. This is due to the compiler assigning a memory location and the variable inheriting whatever value is already in that memory location. Using the value from an uninitialised variable can result in undefined behaviour. Undefined behaviour means executing code whose behaviour is not well defined resulting in data corruption.

Variables declared with a global scope or declared static are initialised to zero. This is because global or static variables are allocated in a separate part of the memory and exist throughout the whole lifetime of the program.

Variable Types

Integer variables hold values that have no fractional part. Signed Integer variables can hold positive or negative values, whereas unsigned integer variables can hold only positive values. Signed variables use one bit to flag whether they are positive or negative. Unsigned variables don't have this bit, so the largest number stored in an unsigned integer is twice as big as the largest positive number in a signed integer. The supported data types in C++ are -

Data type Notes
char Can store -127 to 127 or 0 to 255. 8 bits. Usually used for holding ASCII characters.
char16_t Unsigned integer type. Usually 16 bits. Used for UTF-16 character representation.
char32_t Unsigned integer type. Usually 32-bit bits. Used for UTF-32 character representation.
wchar_t Occupies between 16 or 32 bits depending on the compiler being used. Used for Unicode character representation.
signed char 8 bits. Can store values between -128 to +127. Used for dealing with binary data.
signed short int Usually at least 16 bits. Can store values between –32,768 to 32,767.
signed int Usually at least 16 bits. Can store values between –32,768 to 32,767.
signed long int Usually at least 32 bits. Can store values between –2,147,483,648 to 2,147,483,647.
signed long long int usually at least 64 bits. Can store values between –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
unsigned char 8 bits. Can store values between 0 to 255.
unsigned short int At least 16 bits. Can store values between 0 to 65,535.
unsigned int At least 16 bits. Can store values between 0 to 65,535.
unsigned long int At least 32 bits. Can store values between –2,147,483,648 to 2,147,483,647.
unsigned long long int At least 64 bits. Can store values between 0 to 4,294,967,295.
float Usually 32 bits. Used for storing single precision floating point values.
double Usually 64 bits. Used for storing double precision floating point values.
long double Usually 96 bites. Used for storing long double precision floating point values.
bool 1 byte. Used to represent True of False where true = 1 and false = 0 .

 Variable Scope

The scope of a variable refers to the accessibility of a variable in a given program or function. Any attempt to reference a variable outside its scope will generate a compiler error.

In C++, programming variables can be declared in three places:

  1. Inside a function or a code block. These are local variables and are only valid inside the block they are defined. When a local variable is defined, it is not initialised by the system and must be initialised by the program.
  2. Outside of all functions. These are global variables and can be accessed in any part of the program.
  3. In the function parameters (formal parameter).

In the code example below an attempt to reference an out-of-scope variable will cause the compilation to fail.

#include <iostream>
using namespace std;
int globalvariable = 0; //global variable declaration and value assignment
main()
{
{ // create local scope by use of brackets
int localvariable = 1;//local variable declaration and value assignment
globalvariable = 1; //assign value 1 to global variable
} // end local scope by use of brackets
globalvariable = 2; // assign value 2 to global variable
localvariable = 2; // will not compile. local variable not defined in this scope
}

Clashes in Scope

Usually, when two variables are defined with the same name, in the same scope, the compiler produces a compile-time error but if two variables are defined with different scopes this is not a problem. If a global variable is defined with the same name as a local variable, the local variable takes precedence. To access the global variable use the scope resolution operator. In CPP the scope resolution operator is ::

#include <iostream>
using namespace std;
int v = 0; //create global variable v and assign value 0
main() {
int v = 1; //create local variable v and assignment value 1
::v=2; //set value of global variable i to 1
}

Using Type Definitions

The typedef declaration provides a way to declare an identifier as an alias or shortcut for an existing variable type. The compiler substitutes the identifier with the variable type When compiled. Typedef does not create a distinctive variable type but establishes a synonym for an existing variable type -

typedef int aliasint; //create an alias for int name aliasint
aliasint v=12; //creates int variable v and set to 1

Auto-Typed Variables

Specifies that the type of variable that is being declared will be automatically deducted from its initialiser. A programmer normally specifies the variable type at the variable’s creation however auto keyword in C++ enables a type to be inferred based on the value initially assigned to it. The compiler figures out a suitable data type -

auto count = 3;

The above statement creates the variable count to hold an int value.

Enumerations

An enumeration is a user-defined data type that consists of integral constants called enumerators. An enum variable takes only one value out of many prescribed values and returns a numeric value corresponding to the selected enumeration. These constants can then be used anywhere that an integer can.   Enumerations are defined using the keyword enum followed by the type-name and then the variable-list.

The enumeration list is a comma-separated list of names representing the enumeration values. The variable list is optional because variables may be declared later using the enumeration type name. Although enumerated constants are automatically converted to integers, integers are not automatically converted into enumerated constants.

The following code declares an enumerator called user with values: John, Peter, Mark and Paul, followed by an enumerator variable named id. The numerator variable is set to each name and the integer value output. If no value is set for the enumerated constant then the value of the previous constant is increased by one.

#include <iostream>
enum users{John=1, Peter, Mark=7, Paul}; //declare enumerator & set enumerator list values
int main(){
users id;//declare eumerator type declaration variable id
id=John;//set variable id to John
std::cout << "user id "<< id;//output value of John which is 1
id=Peter;//set variable id to Peter
std::cout << " user id "<< id;//output value of Peter which is 2 (1 more than John)
id=Mark;//set variable id to Mark
std::cout << " user id "<< id;//output value of Mark which is 7
id=Paul;//set variable id to Paul
std::cout << " user id "<< id;//output value of Paul which is 8(one more than Mark)
return(0);
}

Sizeof

The operator sizeof indicates the size in bytes of a variable or a type. Since the size of a variable or data type can differ between computing environments, knowing the size of a variable in all situations can be useful. The syntax of using sizeof is as follows −

sizeof (data type)

Static Variables

Variables of type static are permanent variables within their function or file.  A static variable is declared by putting the word static before the variable type and maybe initialised with a value. 

static int days = 7; //declare static variable 'days' and initialises to 7

Static variables like global variables are initialised to 0 if not explicitly initialised to a defined value.

Static Local Variables - When the static modifier is applied to a local variable, permanent storage is allocated allowing a static variable to maintain its value between function calls. Local static variables are initialised only once, when program execution begins, and retain their value between function calls.

Static Global Variables - A static global variable is known only to the file in which the static global variable is declared. This means other functions in other files have no knowledge of it and cannot change its contents. Although global static variables are still valid their use is not considered good programming practice. Using global variables via namespaces is the preferred method.

The program below calls the function svar() twice outputting the value of variable count twice and increasing the value by 1.

#include <iostream>
using namespace std;
void svar();//declare variable function
int main()
{
int num;
svar();//call variable function
svar();//call variable function
return 0;
}
void svar() {
static int count=5;//declares and initialises static local variable
cout << count;//output variable value
count++;
}

Extern

The extern keyword enables the programmer to declare a variable without defining it. In programs with several files, each file must be aware of the global variables defined outside that file. The extern declaration informs the compiler that a variable by that name and type already exists therefore the compiler does not need to allocate memory for it since it is allocated elsewhere. The syntax is -

extern int x,y;

Although global variables are generally declared at the top of a program, declaring variables as extern has the benefit of enabling global variables to be declared anywhere.  If a function uses a global variable defined later in the same file the global variable can be declared as extern inside the function. When the variable’s definition is encountered, references to the variable are resolved -

#include <iostream>
using namespace std;
extern int count;//extern tells compiler to look for definition elsewhere
int main()
{
cout << count;
return 0;
}
int count=5; //global variable declared after main block

Volatile Variables

The volatile keyword prevents the compiler from applying any optimisations to a variable. The syntax is -

volatile int value;  

Since a value might be changed by code outside the function scope, the system keeps the value of any variable or object current. For instance, the address of a global variable may be passed to an interrupt-driven event that updates a variable without the use of any explicit assignment statements in the program. If the CPP compiler is permitted to optimise certain code on the assumption that the content of a variable is unchanged then this can create problems.

Constants

Constants or literals refer to fixed values a program may not alter after their definition. C++ has two types of constants:

  • Literal Constants
  • Symbolic Constants 

Literal Constants

A literal constant is a value that is typed directly into the source code such as a number, character, or string that may be assigned to a variable or symbolic constant. For instance, in the variable declaration count=10, the variable count is assigned the literal constant 10.

Symbolic Constants

A symbolic constant is an identifier representing a constant value for the program duration.  Whenever a constant value is required the constant name can be used in place of that value throughout the program thus the value of the symbolic constant only needs to be entered only, when it is first defined. Symbolic constants can be defined using the preprocessor directive #DEFINE or the const keyword.

Defining Constants Using #define -The #define directive enables a simple text substitution that replaces every instance of the name in the code with a specified value with the compiler only seeing the final result.  Since these constants don't specify a type, the compiler cannot ensure that the constant has a proper value so it’s better to use the standard constant method. Defining constants using the preprocessor dates back to early versions of the C language.  It is now depreciated and should not be used. The prototype of the define directive is -

#define PI 3.14 

Defining Constants with the Const Keyword - means declaring a variable with a const prefix.  Variables declared to be const can’t be modified when the program is executed. A value is initialised at the time of declaration and is then prohibited from being changed. 

PI is declared as a const variable and a preprocessor directive in the following code.

#define PI 3.14 //set value of constant directive
#include <iostream>
int main()
{
const float PIVALUE= 22.0 / 7; //set value of constant 
printf( "\nValue of constand variable PI %f", PIVALUE);     
printf( "\nValue of constant directive PI %f", PI);     
return 0;     
} 

 

Constants are often fully capitalised by programmers to make them distinct from variables. This is not a requirement but the capitalisation of a constant must be consistent in any statement since all variables are case-sensitive.