MODULE 7
Variables and Data Types in C++
A variable in C++ is a named storage location that can store a value.
Variables are used to store data values, which can be used and manipulated by
the program. C++ is a strongly-typed language, which means that every
variable must be declared with its type before it can be used.
The usefulness of the "Hello World" programs shown in the previous example
is rather questionable. We had to write several lines of code, compile them,
and then execute the resulting program, just to obtain the result of a simple
sentence written on the screen. It certainly would have been much faster to
type the output sentence ourselves.
However, programming is not limited only to printing simple texts on the
screen. In order to go a little further on and to become able to write programs
that perform useful tasks that really save us work, we need to introduce the
concept of variables.
Let's imagine that you were asked to remember the number 5, and also
memorize the number 2 at the same time. You have just stored two different
values in your memory (5 and 2). Now, if again; you were asked to add 1 to
the first number, you should be retaining the numbers 6 (that is 5+1) and 2 in
your memory. Then we could, for example, subtract these values and obtain 4
as result.
The whole process described above is a simile of what a computer can do
with two variables. The same process can be expressed in C++ with the
following set of statements:
a = 5;
b = 2;
a = a + 1;
1
result = a - b;
Obviously, this is a very simple example, since we have only used two small
integer values, but consider that your computer can store millions of numbers
like these at the same time and conduct sophisticated mathematical operations
with them.
We can now define variable as a portion of memory to store a value.
Variables are containers for storing data values. A variable provides us with
named storage that our programs can manipulate.
Each variable needs a name that identifies it and distinguishes it from the
others. For example, in the previous code the variable names were a, b, and
result, but we could have called the variables any names we could have come
up with, as long as they were valid C++ identifiers.
Identifiers
A valid identifier is a sequence of one or more letters, digits, or underscore
characters (_). Spaces, punctuation marks, and symbols cannot be part of an
identifier. In addition, identifiers shall always begin with a letter. They can
also begin with an underline character (_), but such identifiers are -on most
cases- considered reserved for compiler-specific keywords or external
identifiers, as well as identifiers containing two successive underscore
characters anywhere. In no case can they begin with a digit.
C++ uses a number of keywords to identify operations and data descriptions;
therefore, identifiers created by a programmer cannot match these keywords.
The standard reserved keywords that cannot be used for programmer created
identifiers are:
2
alignas, alignof, and, and_eq, asm, auto, bitand, bitor,
bool, break, case, catch, char, char16_t, char32_t, class,
compl, const, constexpr, const_cast, continue, decltype,
default, delete, do, double, dynamic_cast, else, enum,
explicit, export, extern, false, float, for, friend, goto,
if, inline, int, long, mutable, namespace, new, noexcept,
not, not_eq, nullptr, operator, or, or_eq, private,
protected, public, register, reinterpret_cast, return,
short, signed, sizeof, static, static_assert, static_cast,
struct, switch, template, this, thread_local, throw, true,
try, typedef, typeid, typename, union, unsigned, using,
virtual, void, volatile, wchar_t, while, xor, xor_eq
Specific compilers may also have additional specific reserved keywords.
NB: The C++ language is a "case sensitive" language. That means that an
identifier written in capital letters is not equivalent to another one with the
same name but written in small letters. Thus, for example, the RESULT
variable is not the same as the result variable or the Result variable. These are
three different identifiers identifiying three different variables.
Fundamental data types
A data type is a classification of data that tells the compiler or interpreter how
the programmer intends to use the data. It defines the set of possible values
that a variable can have and the operations that can be performed on it.
Data types are important because they help to ensure that programs are correct
and efficient. For example, if a variable is declared to be an integer, the
compiler will not allow it to be assigned a floating-point value. This helps to
prevent errors, such as trying to divide two integers and getting a floating-
point result.
3
The values of variables are stored somewhere in an unspecified location in the
computer memory as zeros and ones. Our program does not need to know the
exact location where a variable is stored; it can simply refer to it by its name.
What the program needs to be aware of is the kind of data stored in the
variable. It's not the same to store a simple integer as it is to store a letter or a
large floating-point number; even though they are all represented using zeros
and ones, they are not interpreted in the same way, and in many cases, they
don't occupy the same amount of memory.
Fundamental data types are basic types implemented directly by the language
that represent the basic storage units supported natively by most systems.
They can mainly be classified into:
Character types: They can represent a single character, such as 'A' or '$'. The
most basic type is char, which is a one-byte character. Other types are also
provided for wider characters.
Examples:
char grade = 'A'; //This assigns the character 'A' to the grade variable.
char symbol = '%'; //This assigns the character '%' to the symbol
variable. Numerical
4
Integer types: They can store a whole number value, such as 7 or 1024. They
exist in a variety of sizes, and can either be signed or unsigned, depending on
whether they support negative values or not.
Examples:
int integerVar = 42; //Declares an integer variable named integerVar and
initializes it with the value 42.
short shortVar = 32767; //Declares a short integer variable named shortVar
and initializes it with the value 32767.
long longVar = 1234567890; //Declares a long integer variable named
longVar and initializes it with the value 1234567890.
5
long long longLongVar = 987654321012345678; //Declares a long long
integer variable named longLongVar and initializes it with the value
987654321012345678.
unsigned int unsignedVar = 100; //Declares an unsigned integer variable
named unsignedVar and initializes it with the value 100.
Floating-point types: They can represent real values, such as 3.14 or 0.01,
with different levels of precision, depending on which of the three floating-
point types is used.
Examples:
float f = 3.14159f; // Declare and initialize a float.
double d = 2.718281828; // Declare and initialize a double.
long double ld = 0.12345678901234567890L; // Declare and initialize
a long double.
6
Boolean type: The boolean type, known in C++ as bool, can only represent
one of two states, true or false.
Examples:
bool isRaining = true; //This line declares a boolean variable named isRaining
and initializes it with the value true, indicating that it is currently raining.
bool isSunny = false; //This line declares another boolean variable named
isSunny and initializes it with the value false, indicating that it is not sunny.
bool isNotRaining = !isRaining; //Here, you use the logical NOT (!) operator
to create a new boolean variable named isNotRaining. It is initialized with the
result of negating isRaining, so it will have the value false because !true is
false. This variable represents the condition "it is not raining."
7
bool isRainAndSun = isRaining && isSunny; //This line creates a boolean
variable named isRainAndSun and assigns the result of the logical AND
(&&) operation between isRaining and isSunny. Since isRaining is true and
isSunny is false, the result will be false. This variable represents the condition
"it is both raining and sunny."
bool isRainOrSun = isRaining || isSunny; //Here, you create a boolean
variable named isRainOrSun and assign the result of the logical OR (||)
operation between isRaining and isSunny. Since isRaining is true, the result
will be true. This variable represents the condition "it is either raining or
sunny."
8
Here is the complete list of fundamental types in C++:
Group Type names* Notes on size / precision
Exactly one byte in size. At least 8
Char
bits.
Not smaller than char. At least 16
char16_t
bits.
Character types
Not smaller than char16_t. At least
char32_t
32 bits.
Can represent the largest supported
wchar_t
character set.
signed char Same size as char. At least 8 bits.
Not smaller than char. At least 16
signed short int
bits.
Integer types Not smaller than short. At least 16
signed int
(signed) bits.
signed long int Not smaller than int. At least 32 bits.
Not smaller than long. At least 64
signed long long int
bits.
unsigned char
unsigned short int
Integer types unsigned int (same size as their signed
(unsigned) unsigned long int counterparts)
unsigned long
long int
Float
Floating-point
Double Precision not less than float
types
long double Precision not less than double
9
Boolean type Bool
Void type Void no storage
Null pointer decltype(nullptr)
Declaration of variables
Declaration of variables in C++ is the process of telling the compiler about
the existence of a variable and its type. This is done by using the following
syntax:
type variable_name;
C++ is a strongly-typed language, and requires every variable to be declared
with its type before its first use. This informs the compiler the size to reserve
in memory for the variable and how to interpret its value. The syntax to
declare a new variable in C++ is straightforward: we simply write the type
followed by the variable name (i.e., its identifier). For example:
These are two valid declarations of variables. The first one declares a variable
of type int with the identifier a. The second one declares a variable of type
float with the identifier mynumber. Once declared, the variables a and
mynumber can be used within the rest of their scope in the program.
If declaring more than one variable of the same type, they can all be declared
in a single statement by separating their identifiers with commas. For
example:
10
This declares three variables (a, b and c), all of them of type int, and has
exactly the same meaning as:
To see what variable declarations look like in action within a program, let's
have a look at the entire C++ code of the example about your mental memory
proposed at the beginning of this lectures and calculate the area of a circle:
Initialization of variables
Initialization of variables in C++ is the process of assigning a value to a
variable when it is declared. This can be done using the assignment operator
(=). For example, the following code would declare and initialize an integer
variable named age to the value 25:
When the variables in the example above are declared, they have an
undetermined value until they are assigned a value for the first time. But it is
possible for a variable to have a specific value from the moment it is declared.
This is called the initialization of the variable.
In C++, there are three ways to initialize variables. They are all equivalent
and are reminds of the evolution of the language over the years:
11
The first one, known as c-like initialization (because it is inherited from the C
language), consists of appending an equal sign followed by the value to which
the variable is initialized:
type identifier = initial_value;
For example, to declare a variable of type int called x and initialize it to a
value of zero from the same moment it is declared, and this type of
declaration is what we have been discussion in data type declaration
examples.
Introduction to strings
Fundamental types represent the most basic types handled by the machines
where the code may run. But one of the major strengths of the C++ language
is its rich set of compound types, of which the fundamental types are mere
building blocks.
An example of compound type is the string class. Variables of this type are
able to store sequences of characters, such as words or sentences. A very
useful feature!
A first difference with fundamental data types is that in order to declare and
use objects (variables) of this type, the program needs to include the header
where the type is defined within the standard library (header <string>):
12
As you can see in the previous example, strings can be initialized with any
valid string literal, just like numerical type variables can be initialized to any
valid numerical literal. As with fundamental types, all initialization formats
are valid with strings:
Strings can also perform all the other basic operations that fundamental data
types can, like being declared without an initial value and change its value
during execution:
13
Single character escape codes
In C++, single character escape codes are special sequences of characters that
begin with a backslash \ and are used to represent non-printable or special
characters. These escape codes are often used in strings and character literals
to represent characters that are otherwise hard to type or visualize directly in
code. Here are some commonly used single character escape codes:
Escape
Meaning Description
code
\n Newline // Newline (\n): Move to the next line
// Carriage Return (\r): Move the cursor to the
\r carriage return
beginning of the line
\t Tab // Tab (\t): Create horizontal indentation
\v vertical tab // Vertical Tab (\v): Effect may vary by platform
// Backspace (\b): Move the cursor one position to
\b Backspace
the left
form feed (page // Form Feed (\f): Used for page breaks or
\f
feed) clearing the screen
\a alert (beep) // Alert (Beep) (\a): Produce a system alert (beep)
14
\' single quote (') // Single Quote (\'): Use within a character literal
\" double quote (") // Double Quote (\"): Use within a string literal
// Question Mark (\?): A regular character; no
\? question mark (?)
special effect
// Backslash (\\): Represent a single backslash
\\ backslash (\)
character
The above examples is represented in the snipaste below
15