The world would be a pretty dull place if everything were always constant. Fortunately, we’re blessed with an abundance of variables that make each day unique. Writing a program in C++ is no different. Variables add depth to the programming language and allow for flexibility and variation while writing code.

In this article, we take a look at what variables are in the context of C++ and how we can use them to add some flexibility into our code. We’ll see why variables are essential and how different variable data types interact with one another through a series of examples.

What Are Variables in C++?

When it comes to programming in C++, a variable is the name of a location the program uses to store a particular piece of data. In using this memory location, variables can be rewritten at any time during a program’s execution. No matter the variable type, all variables must be initialized in C++ before you can use them.

Variable Initialization

Initializing (or declaring) a variable in C++ is not difficult to do. The initialization process is the same regardless of variable type:

variable_type variable_name;

Declaring multiple variables is just as easy:

variable_type variable_name1, variable_name2, variable_name3;

Then, you must choose the variable from a specific list of available options in C++ (more on this below).

You can choose the variable name to be anything as long as it consists of letters (uppercase and lowercase), numbers and the underscore symbol (_). It’s important to note, though, that a variable cannot start with a number. Google even has an extensive style guide for variable naming conventions.

When naming variables, it’s important to use meaningful names to you and anyone analyzing your code. Ideally, variable names are concise and accurately depict what they’re used for. Here are a few examples:

int apples, oranges, bananas;
double dollars, euros;
bool b;

Common Variable Types

Variables can take on many forms in C++, all dependent on how the data type is initialized. Let’s take a look at a few of the commonly used data types that variables can be.

Variable TypeDescription
intUsed to store any whole number.
floatUsed for storing numbers with decimal point values. It can store up to seven decimal places.
doubleUsed for storing numbers with decimal point values. It can store up to 15 decimal places.
boolUsed to store either true or false values.
charUsed to store a single character, letter, number or ASCII value.
stringUsed to store a series of characters.

With some of the most common variable types identified, let’s see how to assign values to them.

Variable Assignment

We’ve initialized some variables in the examples above, but they’re of little use to a program unless we also assign them some values. This assignment can be done at the time of initialization or later in the program. 

This example illustrates the guidelines for simultaneously initializing and assigning a variable:

variable_type variable_name = value;

We simply use the equals sign (=) to tie our variable to a specific value. Here are some actual examples pulled out of code:

int x = 10;
double dollar = 34.55, Euro = 25.24;
bool b = true;

We can also initialize a variable after we’ve declared it:

#include <iostream>

using namespace std;

int main()
{
  int x;

// more code here

  x = 25;

  cout << "x is " << x;

  return 0;
}

Because we declared our variable “x” earlier in the program, we’ll only need to reference the name of the variable and assign a value to it. For this example, we see an output of:

x is 25

If we initialize a value for a variable and then reassign that variable, the new value will replace the old one:

#include <iostream>

using namespace std;

int main()
{
  int num1 = 20;
  num1 = 5;


  cout << "num1 is equal to " << num1;

  return 0;
}

We see the following as our output:

num1 is equal to 5

Even though num1 was initialized to 20, we replaced it with the number 5. The value of 5 erases the 20 in that memory location, and the program outputs 5 for num1.

Why Are Variables Important in C++?

C++ was created as an imperative language. In imperative programming (from the Latin imperare, meaning command) the program provides step-by-step instructions to the computer.

C++ processes are also user-driven. Variables play a key role in building a list of commands and allowing programmers and end-users to input the values necessary to make a program work.

Furthermore, just like classes, variables are a vital way to pass around data in your code. Since a variable represents a memory location, data moves from place to place as variables interact with one other. These interactions can take place through commands such as assignments or operations. As mentioned earlier, not moving or changing data in code would lead to a rigid program.

The Relationship Between Variables and Data Types

In addition to being an imperative language, C++ is also a statically typed language. In a statically typed language, all variables must be initialized and known at the time the program is compiled.

The compiler will check for type errors during compilation and will not need to perform any more checks while running. As a result, this makes statically typed languages faster to use and reduces the likelihood of type-related error.

Data types are linked to variables and not to the values assigned to them. The programmer must specify the type for each variable.

Failing to assign a type to a variable in code leads to a compilation error. Compiling a program like the following results in an error telling us that our “x” was not declared:

#include <iostream>

using namespace std;

int main()
{
  x = 5//oops, we forgot to list what type x is
  cout << "x is " << x;

  return 0;
}

Also, we see an error when we try to assign a value of a different type to an initialized variable:

#include <iostream>

using namespace std;

int main()
{
  int x;
  x="Hello!";

  cout << "x is " << x;

  return 0;
}

Trying to assign a string to a variable that’s initialized as an int does not work.

However, there are instances where data types in C++ can be cast between each other. Although not always an issue, there are times where a value will be demoted, and some data will be lost. Let’s take a look at an example:

#include <iostream>

using namespace std;

int main()
{
  int x = 2.22;
  cout << "x is " << x;

  return 0;
}

Since “x” is an int data type, it recognizes the number we’re assigning to it. Since this data type can only take whole numbers, it cannot handle anything after the decimal point and throws it out. We get the following output from the compiler when compiling this program:

warning: implicit conversion from 'double' to 'int' changes value from 2.22 to 2 [-Wliteral-conversion]
  int x = 2.22;
      ~   ^~~~
1 warning generated.

But the program will run just fine:

x is 2

Even if we convert this into a float or a double, the numbers after the decimal point remain lost.

#include <iostream>

using namespace std;

int main()
{
  int x = 2.22;
  double y = 4.55, z;
  
  z = x + y;

  cout << "z is " << z;

  return 0;
}

This code returns z is 6.55, as int truncates the value of “x” to a whole number before being added to “y.”

Learn C++ With Udacity

Variables are essential to writing code in C++ but are still just one piece of the bigger programming picture.

Enroll in Udacity’s C++ Nanodegree program to build upon your newfound knowledge of variables. Our interactive course is designed by industry experts from world-class companies and allows you to code five real-world projects with guidance at every step of the way.

Enroll in our C++ Nanodegree program today!