Search⌘ K
AI Features

Variables and Literals

Explore how variables store and manage data in C++, covering declaration, initialization, and reassignment. Understand key data types such as integers, floating-point numbers, characters, booleans, and enums, and grasp their memory representation and usage. This lesson lays the groundwork for effective data handling in C++ programming.

Everything a program does revolves around data, such as reading it, calculating it, modifying it, or displaying it. To manipulate data effectively, we need a way to store it in memory and retrieve it when required. In C++, we use variables to do this.

Variables are named storage

In C++, variable has three essential attributes:

  1. Name: A unique identifier we use to refer to the data.

  2. Type: Defines what kind of data can be stored (e.g., a number or a character) and how much space it occupies in memory.

  3. Value: The actual data stored in the memory location.

It is essentially a labeled box in computer memory that holds a specific type of information. Label is the name and the content inside is its value.

A variable is a named memory location that stores a value of a specific type
A variable is a named memory location that stores a value of a specific type

How to create a variable

We must declare a variable before using it. This tells the compiler to reserve space for it. Here's the syntax:

<type> <name>;

Let’s look at a simple example:

C++ 23
#include <iostream>
int main() {
int score; // declaring a variable
score = 10; // assigning a value to it
std::cout << "Score: " << score;
return 0;
}

Let’s break the code down into steps to simplify it:

  • Line 1: We include <iostream> so we can use std::cout for output, just as we did in the previous lesson.

  • Line 3: We define the main function, the entry point of the program.

  • Line 4: We declare an int variable named score. This tells the computer to create a box called score that can store an integer value. At this point, score exists, but it does not have a value yet.

  • Line 5: score = 10; assigns a value to the variable. This tells the computer to put the value 10 inside the score box.

  • Line 6: std::cout << "Score: " << score; prints text to the screen. "Score: " is printed first. Then, the value stored in score is printed.

Initialising variables and reassigning values

Unlike declaring a variable and later assigning it a value, we can give it a value at the moment it is created. This is called initialisation. Here's the syntax:

<type> <name> = <value>;

Let’s revise the above example:

C++ 23
#include <iostream>
int main() {
int score = 10; // initializing a variable
std::cout << "Score: " << score << std::endl;
score = 15; // reassigning the variable
std::cout << "Score: " << score;
return 0;
}
  • Line 4: We declare an int variable named score and assigned a value to it at the same time. This tells the computer to create a box called score that can store an integer value, and put the value 10 inside it.

  • Line 5: std::cout << "Score: " << score; prints text to the screen. "Score: " is printed first. Then, 10 (the value stored in score) is printed. The statement ends with an std::endl. It ends the current line and move the cursor to the next line when printing output. It will become a very large positive number due to a wrap-around.

  • Line 5: score = 15; reassigns a value to the variable. This tells the computer to replace the value 10 with 15 inside the score box.

  • Line 6: This time, std::cout << "Score: " << score; prints "Score: 15", as score equals to 15. Notice, how this is printed in the next line.

Key rules about variables:

  • We can change reassign variables as many times as we need.

  • We cannot change the type after declaration. For example, in a program score stays an int forever.

  • For readability, pick clear, descriptive names: counter, age, temperature_celsius, and not x, y, z.

Supported C++ types

C++ provides different types for storing different types of values, such as numbers, characters, and text. Let’s dive into each of these types in more detail.

Integers

Integers represent whole numbers (no fractions). They use a fixed amount of memory, measured in bytes.

  • Core types: C++ provides several core integer types: short, int, long, and long long. These types mainly differ in how many bytes of memory they use, which affects how small or large the stored number can be. For most modern systems, you can refer the following table. These sizes are common on modern systems, but the C++ standard allows some variation.

Type

Typical size

short

2 bytes

int

4 bytes

long

4 or 8 bytes (depends on the system)

long long

8 bytes

  • Signed/Un-signed: By default, integers are signed, meaning they can hold positive and negative numbers. We can use the unsigned keyword to restrict a variable to non-negative numbers only, effectively doubling its positive range. When a negative value is assigned to an unsigned integer, it converts the value to a larger positive value, based on the size of the type and system.

  • Fixed-width integers: Because the size of int or long can vary between different computer systems, modern C++ often uses fixed-width integers from the <cstdint> header when exact size matters. For example, int32_t and int64_t is guaranteed to be exactly 32 and 64 bits, respectively.

C++ 23
#include <iostream>
#include <cstdint> // Required for fixed-width types
int main() {
short counter = 1; // Standard integer
unsigned int coins = 500; // Cannot be negative
int64_t largeNumber = 9000000000; // Guaranteed 64-bit integer
std::cout << "Integer: " << counter << std::endl;
std::cout << "Unsigned integer: " << coins << std::endl;
std::cout << "Large precise number: " << largeNumber << std::endl;
return 0;
}

Let’s analyze the code above step by step:

  • Line 5: This line creates a variable named counter that stores a whole number. The keyword short tells the program to store this number using less memory than a regular int. Since the value 1 is very small, it easily fits inside a short. Try changing short to int, long, or long long, the output printed to the screen will be the same. Remember, for small values, all integer types behave the same when printed. The difference between them becomes important only when we need to store very large numbers.

  • Line 6: This line declares a variable named coins that stores a whole number. The type unsigned int means the variable can store only non-negative values. Try changing its value to a negative number and notice the change in output.

  • Line 7: This line declares a variable named largeNumber that stores a very large whole number.The type int64_t guarantees that the number is stored using exactly 64 bits (which maxes out around 2 billion).

  • Lines 9-11: The std::count statements are printing variables values.

Floating-point numbers

These types represent numbers with fractional parts (decimals).

  • float: Single precision, usually 32 bits.

  • double: Double precision, usually 64 bits. This is the default choice for decimals in C++ because it balances precision and performance well.

  • long double: Extended precision for scientific calculations requiring extreme accuracy, typically ≥ 64 bits.

C++ 23
#include <iostream>
int main() {
float sensorReading = 20.59f; // Single precision
double dailyAverage = 23.125; // Double precision (default)
long double scientificValue = 23.125000000123L; // Extended precision
std::cout << "Sensor reading (float): " << sensorReading << std::endl;
std::cout << "Daily average (double): " << dailyAverage << std::endl;
std::cout << "Scientific value (long double): " << scientificValue << std::endl;
return 0;
}

Let’s analyze the code above step by step:

  • Line 4: This declares a float variable named sensorReading and initializes it with 20.59f. The f tells C++ to treat the number as a float.

  • Line 5: This declares a double variable named dailyAverage and initializes it with 23.125.

  • Line 7: This declares a long double variable named scientificValue for extra precision. The L tells C++ to treat the number as a long double.

Characters

The char type stores a single character, like 'a', 'Z', and '7'. Although it looks like a character, the computer actually stores it as a number (usually ASCII) that represents that character. See an example below.

C++ 23
#include <iostream>
int main() {
char league = 'A';
char jersey_num = '7';
std::cout << "League: " << league << ", Jersey number: " << jersey_num;
return 0;
}
  • Lines 4–5: Two char variables are declared; league stores the character 'A' and jersey_num stores the character '7'.

Booleans

A boolean variable represent a logical truth value. It is declared using the bool keyword and its value can only be true or false.

C++ 23
#include <iostream>
int main() {
bool isActive = true;
bool isOverweight = false;
std::cout << "Activity Status: " << isActive << std::endl << "Overweight Status: " << isOverweight;
return 0;
}
  • Lines 4-5: Two bool variables are declared; isActive stores true and isOverweight stores false.

  • Line 7: We print our delcared boolean variables. Note that when printed, true outputs as 1 and false as 0 unless we configure the output stream differently.

Enumerations (enum)

Sometimes we need a variable that can only hold one value out of a small, fixed set of options, like days of the week or difficulty levels in a game. An enumeration (enum) allows us to define our own type with named integer constants.

C++ 23
#include <iostream>
enum Difficulty { // Enums are stored as integers internally (0, 1, 2...)
EASY,
NORMAL,
HARD
};
int main() {
Difficulty currentLevel = NORMAL;
std::cout << "Difficulty Level: " << currentLevel << "\n";
return 0;
}

Let’s break down our code into steps:

  • Lines 3–7: We define a new type named Difficulty. By default, EASY is 0, NORMAL is 1, and HARD is 2.

  • Line 10: We create a variable currentLevel of type Difficulty and assign it NORMAL.

  • Line 11: Printing the enum outputs its underlying integer value, i.e., 1. Try changing value of currentlevel at line 10, to notice the change in the output.

void: The “no value” type

void is a special type used to indicate the absence of a value. You can’t create variables of type void, because there’s nothing to store. Instead, you’ll mainly encounter void when working with functions that don’t return anything. We'll see this in detail, later.

For now, it’s enough to think of void as meaning: this code does something, but it doesn’t give a value back.

Derived types (a glimpse)

The aforementioned types are fundamental types. C++ allows us to build complex derived types from these building blocks. While we will cover these in depth in later chapters, you should recognize their names:

  • Arrays – fixed-size sequences of elements.

  • Pointers – variables that hold memory addresses.

  • References – aliases to existing objects.

  • Function types – representing methods with given parameters and return values.

For now, it is enough to know they exist.

So far, we have built the foundation of all C++ data handling: variables and literals. We now know that every variable has a type, name, and value; that C++ offers a rich set of fundamental types for integers, floating-point numbers, characters, booleans, and enums; and that literals are the fixed values we use to initialize and manipulate those variables. With these tools, we are ready to dive deeper.