How To Write C++ Variables

Variables are an important part of any software application.

However, every programming language has different variable characteristics. Some languages have special syntax. There is also the question of typing - some languages are statically typed (which means you must specify a variable's data type before value assignment) while others are dynamically typed (which means a variable can assume any value, with no specification required).

There is much to understand about a language's variables before starting to write code. With that in mind, this article will teach you how to write C++ variables properly, which will save you time and grief later on in your programming journey.

Table of Contents

You can skip to a specific section of this C++ tutorial using the table of contents below:

What Are C++ Variables?

Variables are the fundamental blocks on which a programming language is built. They can be understood as named memory locations that store data temporarily. Variables can change while the program is running.

In most languages (C++ included), each variable has a type, which determines its size and layout, the range of values that it can store in memory, and the set of operations that can be applied to it.

A variable is just the name given to a memory location. Therefore, when the program runs and a variable undergoes different operations, the change reflects in that memory location too. Before using any C++ variable, it has to be declared and sometimes, defined too.

Throughout the rest of this article, I will discuss the characteristics of variables in C++, their types, and how to declare and define them.

Type of C++ Variables (By Data Type)

There are various categories into which the variables in C++ can be divided on the basis of their data types. These are:

  • **int: **Variables of this type hold integer value (whole numbers).
  • **char: **These variables hold character values like ‘a’, ‘H’, ‘M’, ‘l’, ‘x’, etc.
  • string: Stores text like “Hello World”.
  • bool: Stores either true or false.
  • double: This variable stores double-precision floating-point value.
  • **float: **This stores single-precision floating-point value.
  • **void: **This variable represents the absence of type.
  • **wchar_t: **A wide-character type.

Naming C++ Variables

Before I show you how to declare and define variables, here are a few rules to take note of while naming the variables. Note that while I will be calling them names in this article, C++ variable names are also called identifiers.

In general, it is considered a best practice that you pick a variable name that tells the reader about the data it represents. For instance, if you need a variable name for storing the name of a student, you may call it stuName.

Here are some other rules to follow while naming variables:

  1. The names can range from 1 to 255 characters. However, the recommended name size is 1 to 31 characters.
  2. All variable names should begin with either a letter of the alphabet or an underscore(_).
  3. After the first letter in the name, it can contain letters or numbers.
  4. Special characters or spaces are not allowed.
  5. Variable names are case sensitive. While there is no limitation on using all uppercase letters in a name, it is usually used to identify constant variables (which are variables whose values are not expected to change over time). Because of the case-insensitivity of C++ variables, myChar, mychar, myCHAR, and Mychar are all recognized as different variable names in C++.
  6. You cannot use C++ keywords as variable names. Here is the list of these keywords and reserved words:
asm else new this
auto enum operator throw
bool explicit private true
break export protected try
case extern public typedef
catch false register typeid
char float reinterpret_cast typename
class for return union
const friend short unsigned
const_cast goto signed using
continue if sizeof virtual
default inline static void
delete int static_cast volatile
do long struct wchar_t
double mutable switch while
dynamic_cast namespace template
And bitor not_eq xor
and_eq compl or xor_eq
bitand not or_eq

Declaring and Defining C++ Variables

To create or declare a variable, the type has to be specified. The syntax for variable declaration looks like:

type variable;

where type is a valid C++ data type (such as int) while the variable is the name of the variable (such as a or myVar). Therefore, to create a variable that should store an integer:

int myNum;

Similarly, if you need to create a variable that should store a character:

char myChar;

After specifying the type of these variables, we need to define them. Defining a variable means assigning any value to the variable.

The equal sign is used to assign values to variables that you have declared. You can declare and define variables at the same time as follows:

int myNum = 62;

cout << myNum;

The output in this case will be:

62

Another way of doing this is:

int num1, num2;

num1 = 20;

num2 = 78;

cout << num1;

cout << num2;

The output here is:

20

78

To summarize, variable declaration refers to introducing a variable before its first use. Variable definition is a part where it is assigned a location in memory and and value.

If you do not define a variable and later call it in a function, it will pick up a random garbage value.

Declaration of a variable is important at the compilation stage to assure the compiler that at least one variable exists for the given type. Separately, the definition of the variable is used at the time of linking the program.

Here’s an example of a program where the variables are declared outside the main function but defined inside it.

#include <iostream>

using namespace std;

 

// Variable declaration:

extern int x, y;

extern int z;

extern float a;

 

int main () {

   // Variable definition:

   int x, y;

   int z;

   float a;

 

   // actual initialization

   x = 15;

   y = 25;

   z = x + y;

 

   cout << z << endl ;

 

   a = 70.0/3.0;

   cout << a << endl ;

 

   return 0;

}

The output when the above code is executed is:

40

23.3333

Variable Initialization in C++

It is important to understand what happens in memory when C++ variables are stored and updated.

When information is stored in a variable, it is stored at a particular memory location. When it is updated, it is stored at a different address.

Unlike other programming languages, C++ doesn’t initialize variables to give value such as zero. Instead, uninitialized variables pick up random garbage value which happens to be at that location at the time of compilation.

There are two types of variable initialization in C++:

Static Initialization

The first type of C++ variable initialization is static initialization.

In this case, the variable is given a value in advance and therefore, in the program whenever it is called, it acts as a constant.

Dynamic Initialization

The second type of C++ variable initialization is dynamic initialization.

This refers to assigning the value at run time. In this case, the value can be altered every time the program is run.

Here are some methods that can be used to initialize a variable in C++:

Method 1: Declaring and initializing a variable

int x = 10;

Method 2: Initializing a variable using parenthesis

int x(10);

Alternatively, for a class type:

struct X {

	X(int);

};

X x(10);  

// This statement is to construct x;

Method 3: Initializing a variable using braces

int x{10};

Method 4: Declaring a variable using auto class

auto x=10;

‘auto’ is a keyword that is used to tell the compiler the type of the variable upon its initialization.

Method 5: Declaring and Initializing a variable through ‘auto’ keyword with parenthesis

auto x(10);

Method 6: Declaring and Initializing a variable through ‘auto’ keyword with braces

auto x{10};

Method 7: Dynamic Initialization

int x;

cin>>x;       	

In the next section of this article, I discuss scope in the context of C++ variables.

Scope of C++ Variables

In software development, scope can be understood as the region of a program. If a variable is 'globally scoped', then it is available globally throughout the program. If a variable is 'locally scoped', then its availability is restricted in some manner.

When I talk about the scope of variables in C++, I am specifically referring to the places in the program where they can be used or called.

As an example, consider the following program:

int main {

 

//Some code

 

}

In the above program, any variable that is declared inside these curly braces will have a scope limited within these braces.

That means if you declare a variable inside the main function and try to use it outside of that function, then this will result in compilation error.

As implied at the beginning of this sectino, C++ variables can be divided into two broad categories depending on their scope:

**1.**  	**Global Variables**

Variables that are defined outside of all the functions and can be accessed anywhere in the program are called global variables.

They hold their value through the lifetime of the program.

Usually, they are declared at the top of the program. Here is an example:

// Program to illustrate 

// usage of global variables 

#include<iostream>

using namespace std;

 

// global variable

int globalVar = 10;

 

// global variable accessed from

// within a function

void display()

{

	cout<<globalVar<<endl;

}

 

int main()

{

	display();

	globalVar = 40;

	display();

}

The output here will be:

10

40

Since the variable was declared outside of all functions, it could be accessed or updated anywhere in the program.

**2.**  	**Local Variables**

Variables that are declared within a function or a block are referred to as local variables.

As the name suggests, their scope is local and cannot be accessed outside the function in which they are declared. Doing so will result in a compilation error.

Here is an example:

// Program to illustrate 

// usage of local variables 

#include<iostream>

using namespace std;

 

void func()

{	

	// this variable cannot be 

	// accessed outside this function

	int lvl=5; 	

}

 

int main()

{

	cout<<"You have reached level "<<lvl;

  	

	return 0;

}

The above program, on execution, will result in compilation error since the variable was declared in function func() and therefore, it could not be accessed outside of it.

Here's how you could fix the problem:

#include<iostream>

using namespace std;

 

void func()

{	

	// this variable cannot be 

	// accessed outside this function

	int lvl=5; 

	cout<<lvl;

}

 

int main()

{

	cout<<" You have reached level ";

	func();

  	

	return 0;

}

Output:

You have reached level 5

What If Local and Global C++ Variables Have The Same Name?

In a program where there is a global variable and a local variable with a same name, when a function calls a variable with that name, what will happen?

Which variable will get precedence?

Let's figure this out by looking at an example:

#include <iostream>

using namespace std;

// This is a global variable

char myVar = 'G';

char myFunc() {

   // This is a local variable

   char myVar = 'L';

   return myVar;

}

int main()

{

   cout <<"Function call: "<< myFunc()<<endl;

   cout <<"Value of myVar: "<< myVar<<endl;

   myVar='M';

   cout <<"Function call: "<< myFunc()<<endl;

   cout <<"Value of myVar: "<< myVar<<endl;

   return 0;

}

Output:

Function call: L

Value of myVar: G

Function call: L

Value of myVar: M

As seen in the above program, when I changed the value of myVar in the main function, it only changed the value for global variable myVar while the value of local variable myVar remained the same because it was limited to function myFunc().

Final Thoughts

Understanding how to create C++ variables is a critical piece of knowledge for any C++ developer. The characteristics and scope of C++ variables is also tremendously important.

In this article, I explained C++ variables (and their characteristics, scope, and attributes) in detail. Feel free to use this article as a guide if you ever get stuck on variable-related problems in the future.


Written on September 10th, 2020