Variables

What is a variable

Variables are how we store data to handle later. They are a crucial part of any multistep process. You can think of variables as your program's memory.

In this chapter, you will learn how to create and use variables. You will also learn how to store user-input so that you can use it.

By the end of this chapter, you will be able to make a calculator that takes user input and spits out an answer.

Declaring and Defining a variable

We must create a variable before we can use it. Declaring it announces its presence and allocates space for the variable.

datatype variable_name = value;

Replace datatype with the type of information the variable will store. For example, int lets the variable store an integer (a number without decimal points). Trying to store a value that doesn't match the datatype can lead to errors, loss of data, or crashes.

variable_name is the name used to refer to the variable later. You can name it whatever you want.

value is the initial value held by the variable.

int example_variable = 7;
std::cout << example_variable << " - " << example_variable + 3;

This code declares and prints an int variable. The output will be 7 - 10.


You must declare a variable above where you use it. Using a variable before you declare it asks the program to use something that doesn't exist yet.

std::cout << variable_example; // ERROR: variable not found
int variable_example = 10;

This code will not compile.


You can change a variable's value with the assignment operator (=).

#include <iostream>

int main()
{
    int example_variable = 4;
    std::cout << example_variable << ` - `;
    example_variable = 7;
    std::cout << example_variable;
}

The console outputs 4-7 because example_variable changes between the outputs.

Naming restrictions & recommendations

Variable names can contain letters, numbers, and underscores. However, they cannot begin with a number. You cannot include symbols or spaces in variable names.

Variable names are case-sensitive, meaning varName differs from varname.

Variable names that describe their use are important for code readability. Finding out what RemainingLoanPayment does is much easier than rlp.

You can use underscores and capitalization to separate words.

camelCase capitalizes the first letter of each word after the first. snake_case uses underscores to separate words. PascalCase capitalizes the first letter of every word. If you want to learn more about naming conventions, you can check out this article.

Numeral data types (int, float, double)

We will cover number variables initially, as we need them for a calculator program. As the course progresses, we will cover more data types and how to work with them.

The int datatype stores integers, which are numbers without decimal points.

The float datatype stores floating point numbers, which are numbers with decimal points.

The double datatype also stores floating point numbers. It occupies double the memory and offers higher precision than float.

std::cin & storing multiple inputs

Just like std::cout controls the console output, std::cin controls the console input.

int myVariable;
std::cin >> myVariable;

The extraction operator (>>) pushes the value from std::cin into myVariable.

This is different from the insertion operator (<<) used for std::cout. The arrows indicate the transfer of data from the left side to the right.

The code execution freezes at std::cin until the user inputs something into the console window.

#include <iostream>

int main() {
    // Creating a variable that we can store integer data in
    int variable; 
    // Program execution freezes and awaits the users' input.
    // The input is placed into `variable`
    std::cin >> variable; 
    // The inputted value is used for the output
    std::cout << variable*2;
}

This program takes an integer input and outputs the double of that input.


To make a calculator that takes 2 inputs and adds them we need to:

  1. Declare a float variable for each input.
  2. Tell the user what type of input they should give.
  3. Use std::cin to get user input twice to assign value to the variables.
  4. Output the sum of the 2 variables.
#include <iostream>

int main 
{
	std::cout << "Input the 2 numbers you want the sum of";

	float input1;
	float input2;
	std::cin >> input1;
	std::cin >> input2;

	std::cout << "The sum of " << input1 << " + " << input2 << " is " << input1 + input2;
}

The float data type can only handle numbers. Our program breaks if the user inputs invalid inputs, such as text.

In future lessons, you will learn how to ensure that the user inputs the correct type of input. For now, be aware that this program requires the user to input a number.

Casting datatypes

You've probably heard of binary before. Data is stored as 1's and 0's. The datatype determines the size of the variable in memory (how many 1's and 0's are used) and how to handle the 1's and 0's.

The integer 4 looks like this in binary: 00000000 00000000 00000000 00000100 The float 4 looks like this in binary: 01000000 10000000 00000000 00000000 If this binary value was an integer, it would be 1 082 130 432.

We perform type casting when assigning an int value to a float. Type casting is the compiler interpreting the value of one datatype and trying to fit it into another. This is how we avoid numbers turning from 4 to 1 billion when changing datatypes.

int int_example = 3;
// Even though the binary data differs, the program adjusts it to contain the same value in a different format.
float float_example = example;
// This outputs 3
std::cout << float_example;

Casting can lead to unintended behavior, loss of data, or in the cases where the datatypes are a complete mismatch, cause errors.

float variable1 = 3.6;
int variable2 = variable1;
std::cout <<variable1 <<" | "<< variable2;
3.6 | 3

Here, the float value is cast to an integer, resulting in the loss of decimal point data.

Trying to fit a decimal number into an integer cuts off the data after the decimal instead of rounding it.

int var = 4.999 holds 4.


The examples above are implicit casts.

You can explicitly cast a value by indicating the desired datatype in front of the value, using either of these syntaxes.

int variable1 = int(value);
int variable2 = (int)value;

Casting to avoid type interference

Many run into problems using math operators on integers and expecting a decimal answer.

Intger division takes places when integers are divided together. The number they evaluate as will also be an integer. Decimal numbers are not considered.

std::cout << 8/3;

This program outputs 2.

This also happens if you use integers to assign a float variable. Because the right side of the equation is evaluated before the assignment.

float var = 8/3; // var will hold the value 2.0

Casting datatypes before a calculation can sometimes be required.

#include <iostream>

int main() {
	std::cout << "input the 2 integers you want to divide.";
	int in1; 
	int in2;
	std::cin >> in1;
	std::cin >> in2;
	std::cout << float(in1) / float(in2);
}

A value without decimal points will be evaluated as an int.

4 is an int.

A value with decimal points will be considered a double. This is true even if the decimal point doesn't affect the number.

3.0 and 3. are doubles.

Adding an f after the decimal will make it into a float.

3.f and 3.0f are floats.

Variable Operators and Expressions

You aren't required to initialize a variable.

int example_variable; // This will compile

However, you want full control of your variables and their content. Using a variable before assigning a value to it can lead to errors, unintended behavior, or crashes.

When we get a user input, we assign a value to the variable right after declaring it, so there's no problem.


You can set the value of a variable to itself + another number. This way, you change it based on its current value.

int example = 3;
example = example + 4;
std::cout << example; // will output 7

You can't do this when declaring it.

int var = var + 1; // this will not compile

Assignment Operators

Assignment operators set or change the value of a variable. Their purpose is to set the variable on the left to the value on the right. They are not the same as the equal sign in maths.

It will not balance out equations, and it will not work if you put the variable on the right side.

int var = 0;
var = 8; // Variable on left, the expression on the right, compiles and runs well.

var + 3 = 8; // Does not balance, will not compile. 
8 = var; // Does not balance, will not compile.

The basic assignment operator is the = symbol. We can add an arithmetic operator before the equals sign to change the assignment operator behavior to modify the left-side variable with the right-side value, rather than replacing the left side.

#include <iostream> 

int main() 
{
	int var = 3;
	// Doubles the value of var
	var *= 2;
	// Adds 4 to var
	var += 4;
	// 3*2+4 = 10, so it will output 10
	std::cout << var;
}
10

The line var += 4 is equivalent to var = var + 4. += clearly shows that the intention of the line is modifying the variable with what is on the right. The same concept can be used with the other operators. *=, /=, -=, +=, %=.

Upgrading our calculator program

In the previous chapter, we made a simple calculator that added two numbers together.

#include <iostream>

int main()
{
    std::cout << 5+4;
}

With the ability to store user inputs in variables, we can upgrade it.

Now we can make a functioning calculator program that someone other than us could use.

#include <iostream>

int main() 
{
	// Declare variables to store our user's input in
	float input1;
	float input2;
	// Give the user information about what the program does, and tell them what input to give
	std::cout << "Input the first number you want to add\n";
	// Get his first input and store it in input1
	std::cin >> input1;

	// Repeat the process for the second input
	std::cout << "Input the second number you want to add\n";
	std::cin >> input2;

	// Output the sum in an understandable way.
	std::cout << "\n" << input1 << " + " << input2 << " = " << input1 + input2;
}
Congratulations!

You have now created your first program that takes user input. From here, you can further modify the program to incorporate more inputs or use different operators.

Questions

Questions

Questions

Questions

Questions

Questions

Questions

Questions

Questions