DEV Community

Cover image for C++ from the beginning - variables
Chris Noring for Microsoft Azure

Posted on • Updated on

C++ from the beginning - variables

TLDR; This is the second part in a series about C++. In this part, you learn about variables, what they are, what types exist and how you can use them to track state in your app.

 The full series

Resources

 What's a variable and what to use it for

When programming, you write a set of instructions to be executed one after another, from top to bottom. Say you perform a calculation, or you have some other piece of data that you want to save and refer to later, at that point, you need a variable. A variable is a named reference holding a piece of data that remembers the data you assigned to it. Here's an example:

int sum = 3 + 5;
Enter fullscreen mode Exit fullscreen mode

In this case, you have the variable sum and it remembers the result of a computation, of 3 being added to 5. Where you later to refer to this variable, it's able to resolve into the value, where you to print it for example, like the below:

int sum = 3 + 5;
statement;
statement;
statement;
statement;
cout << sum; // prints 8
Enter fullscreen mode Exit fullscreen mode

In the above code, you have just that scenario, a computation on the first row, several statements the program executes when run, and finally, you refer to sum again and it remembers its value.

Now that you see the idea of having a variable, let's look at some concepts around variables that we need to know about.

Declare a variable, it has a type and a name

You've seen a variable being created so far, the variable sum, but what did happen? Let's look at it again:

int sum;
Enter fullscreen mode Exit fullscreen mode

Above you are declaring a variable, you tell the program a variable exists by a certain name sum and a type. See the above as a combination of type and name:

<type> <name>;
int sum;
Enter fullscreen mode Exit fullscreen mode

The type in this case is int and stores whole numbers like 11 or 1000 and so on;

Initialise a variable, type, name, and value

To initialise a variable is similar to declaring a variable. The difference is that when you initialise something you tell the program a variable exists by a certain name AND that it has a starter value, for example:

int players = 2;
Enter fullscreen mode Exit fullscreen mode

 Different variable types

So far, you've seen the type int, storing whole numbers, what other types are there?

Well, let's list what we refer to as the basic data types, in some programming languages referred to as primitives

  • int, stores whole numbers, for example, 6 or 23
  • float and double, stores numbers with decimals. 7 and 15 decimals for float and decimals respectively, for example, 3.14
  • char, stores a single character, like a or b, here's an example, 'a', note the use of single quote.
  • bool, stores true or false. Here's an example canSave = false;

Example with int and float

Let's look at an example of how our usage of float and int would differ:

int players;
float PI = 3.14;
Enter fullscreen mode Exit fullscreen mode

Above, players makes sense to be a stored to be a whole number, there's no part of a player. For PI, which is decimal with many many decimals, a float is at least needed. Even then, it's an approximation. You most likely need to make it a double and even then it doesn't hold enough decimals.

Operators like + - * / %

For number type variables, operators plays a part in helping to perform calculations, to add, subtract, multiply and so on. Here's some operators you are likely to use:

  • +, adds two numbers together, for example 1 + 1 is 2.
  • -, removes right side from left side, for example, 1 - 1 is 0.
  • /, divides left side, right side times, for example 4 /2 is 2.
  • *, multiplication, multiplies the values with each other, for example, 3 * 4 is 12.
  • %, modulo, gives the left over when doing a division, for example, 5 % 2 is 1.

 Naming

Naming is important topic. It's also a topic where folks don't usually agree on what to use. There's one golden rule though, be consistent, use the same way of naming throughout.

To quote the creator of C++ Bjarne

Name a variable (function, type, whatever) based on what it is or does. Choose meaningful name; that is, choose names that will help people understand your program Bjarne on naming

Some has suggestion Pascal casing for variables:

int account_total = 0;
Enter fullscreen mode Exit fullscreen mode

and camel case for functions (more on functions in future part in this series):

int calculateTotal() {}
Enter fullscreen mode Exit fullscreen mode

Example a calculator

To use your knowledge about variables, types, and operators, lets implement a calculator program below.

  1. Create a file app.cpp and give it the following content:
   #include <iostream>
   using namespace std;

   int main()
   {
     int first_value = 3;
     int second_value = 5;
     float nominator = 7;
     float denominator = 2;
     int sum = first_value + second_value;
     float quotient = nominator / denominator;

     cout << "Sum is: " << sum << "\n";
     cout << "Quotient is: " << quotient << "\n";
     return 0;
   }
Enter fullscreen mode Exit fullscreen mode
  1. Compile the app with g++:
   g++ app.cpp
Enter fullscreen mode Exit fullscreen mode
  1. Run the app:
   ./a.out # Linux, macOS
   a.out # Windows  
Enter fullscreen mode Exit fullscreen mode

It should print out:

   Sum is: 8
   Quotient is: 3.5
Enter fullscreen mode Exit fullscreen mode

Summary

In this article, you've learned about some basic variables, what they are, why use them and some basic variable types. You should now be better setup to use them to make your programs perform calculations and remember responses and making them easier to read.

Top comments (0)