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:
Name: A unique identifier we use to refer to the data.
Type: Defines what kind of data can be stored (e.g., a number or a character) and how much space it occupies in memory.
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.
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:
Let’s break the code down into steps to simplify it:
Line 1: We include
<iostream>so we can usestd::coutfor output, just as we did in the previous lesson.Line 3: We define the
mainfunction, the entry point of the program.Line 4: We declare an
intvariable namedscore. This tells the computer to create a box calledscorethat can store an integer value. At this point,scoreexists, 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 value10inside thescorebox.Line 6:
std::cout << "Score: " << score;prints text to the screen."Score: "is printed first. Then, the value stored inscoreis 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:
Line 4: We declare an
intvariable namedscoreand assigned a value to it at the same time. This tells the computer to create a box calledscorethat can store an integer value, and put the value10inside it.Line 5:
std::cout << "Score: " << score;prints text to the screen."Score: "is printed first. Then,10(the value stored inscore) is printed. The statement ends with anstd::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 value10with15inside thescorebox.Line 6: This time,
std::cout << "Score: " << score;prints"Score: 15", asscoreequals to15. 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
scorestays anintforever.For readability, pick clear, descriptive names:
counter,age,temperature_celsius, and notx,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, andlong 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 |
| 2 bytes |
| 4 bytes |
| 4 or 8 bytes (depends on the system) |
| 8 bytes |
Signed/Un-signed: By default, integers are signed, meaning they can hold positive and negative numbers. We can use the
unsignedkeyword 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
intorlongcan vary between different computer systems, modern C++ often uses fixed-width integers from the<cstdint>header when exact size matters. For example,int32_tandint64_tis guaranteed to be exactly 32 and 64 bits, respectively.
Let’s analyze the code above step by step:
Line 5: This line creates a variable named
counterthat stores a whole number. The keywordshorttells the program to store this number using less memory than a regularint. Since the value1is very small, it easily fits inside ashort. Try changingshorttoint,long, orlong 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
coinsthat stores a whole number. The typeunsigned intmeans 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
largeNumberthat stores a very large whole number.The typeint64_tguarantees that the number is stored using exactly 64 bits (which maxes out around 2 billion).Lines 9-11: The
std::countstatements 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.
Let’s analyze the code above step by step:
Line 4: This declares a
floatvariable namedsensorReadingand initializes it with20.59f. Theftells C++ to treat the number as afloat.Line 5: This declares a
doublevariable nameddailyAverageand initializes it with23.125.Line 7: This declares a
long doublevariable namedscientificValuefor extra precision. TheLtells C++ to treat the number as along 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.
Lines 4–5: Two
charvariables are declared;leaguestores the character'A'andjersey_numstores 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.
Lines 4-5: Two bool variables are declared;
isActivestorestrueand isOverweightstoresfalse.Line 7: We print our delcared boolean variables. Note that when printed,
trueoutputs as1andfalseas0unless 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.
Let’s break down our code into steps:
Lines 3–7: We define a new type named
Difficulty. By default,EASYis 0,NORMALis 1, andHARDis 2.Line 10: We create a variable
currentLevelof typeDifficultyand assign itNORMAL.Line 11: Printing the enum outputs its underlying integer value, i.e.,
1. Try changing value ofcurrentlevelat 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.