C++ from the beginning - variables
Tags: cpp, tutorial, beginners
Published: 2021-11-03 22:07:26

---
title: C++ from the beginning - variables
published: true
series: C++ beginners
description: Second part of a C++ series describing variables in C++
tags: cpp, tutorial, beginners
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z28n4kx2gosx4kzbmfpa.jpg
---

> 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

- [Your first program](https://dev.to/azure/c-from-the-beginning-2o2l)
- Variables, **you are here**
- [Working with input and output](https://dev.to/azure/c-from-the-beginning-input-and-output-5ad0)
- [Functions](https://dev.to/azure/c-from-the-beginning-functions-5cnl)
- [Control flow](https://dev.to/azure/c-from-the-beginning-control-flow-21jg)
- Working with files
- Pointers
- Error management
- Structs and Classes

## Resources

- [CPP Snippets for VS Code](https://marketplace.visualstudio.com/items?itemName=chris-noring.cpp-snippets&ssr=false#overview)
- [C++ module](https://docs.microsoft.com/en-us/learn/modules/cpp-first-program?wt.mc_id=academic-0000-chnoring)

## 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:

```cpp
int sum = 3 + 5;
```

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:

```cpp
int sum = 3 + 5;
statement;
statement;
statement;
statement;
cout << sum; // prints 8
```

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:

```cpp
int sum;
```

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:

```cpp
<type> <name>;
int sum;
```

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:

```cpp
int players = 2;
```

## 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:

```cpp
int players;
float PI = 3.14;
```

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](https://www.stroustrup.com/bs_faq2.html)

Some has suggestion Pascal casing for variables:

```cpp
int account_total = 0;
```

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

```cpp
int calculateTotal() {}
```

## 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:

   ```cpp
   #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;
   }
   ```

1. Compile the app with `g++`:

   ```bash
   g++ app.cpp
   ```

1. Run the app:

   ```bash
   ./a.out # Linux, macOS
   a.out # Windows  
   ```

   It should print out:

   ```output
   Sum is: 8
   Quotient is: 3.5
   ```

## 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.