Chapter 2: Variables and Values
In this chapter, we shall be digging deep into some building blocks of C++ program. We would be experimenting with concepts like declarations, reserved words, assignments, numerical values, identifiers, and variables.
Integer Values
Integers are numeric values that are whole numbers. So numeric values in factional parts is not an integer value in C++ code. For example, five (5) is an integer. Furthermore, the integer can either be zero, negative, or positive. Other examples of integers include 6, - 13, and – 2006, but 5.4 is not an integer because it is not a whole number. Take a look at Code 2.1 below as it shows how an integer value can be employed in C++ code:
Code 2.1
#include <iostream>
int main () {
st::cout << 5<< ‘\n;
}
If you notice, unlike the other codes we wrote earlier, this code does not make use of quotation marks (“). The number 5 will still appear even when there are no quotes. Also, the expression “\n
” signifies a single newline character. But if you’re writing code with multiple characters comprising of a string, then you need to use double quotes (“). In C++, a single character is enclosed in single quotes (‘) and represents a distinct type of data. Check out this example below:
Code 2.2
#include <iostream>
int main () {
std::cout << “5\n”;
}
Code 2.1 and Code 2.2 may seem similar, but they are quite different. Code 2.1 prints the value of number five, while Code 2.2 above prints a message containing the digit five. The difference here may seem unimportant, but in later in this chapter, we’d show you how the presence and absence of quotes in a code can make a big difference in its output. In the statement std::cout << “5\n”; sends a message to the output stream, which is the string “5\n”
. On the other hand, the statement std::cout << 5 << ‘\n’; sends two messages to the output string; the first is the integer value 5, and the second is the newline character ‘\n’
.
In some cases, developers could write the same Code 2.2 in a different way:
Code 2.3
std::cout << 5 << std::endl;
Now, even though Code 2.2 and Code 2.3 behave exactly alike, they do not mean exactly the same thing. The std::endl
expression involves a newline character, and it also performs additional work that isn’t necessary. Programs meant for significant printing would execute faster if you end their output line with ‘\n’
rather than std::endl
. However, we can ignore the difference in speed when we’re printing on the console, but the difference in speed is not negligible when you’re printing on other output streams or files. Nonetheless, we’ve been making use of the ‘\n’
most times for printing newlines because it is a good habit to form as a beginner as it involves only a few keystrokes. Likewise, the three major modern computing platforms; Apple macOS, Microsoft Windows, and Linux, handle newlines differently.
Also, in C++ code, integers cannot contain commas. In other words, we can write the numbers nine thousand, five hundred and twenty-four as 9524 and not 9,524. Modern C++, however, supports single quotes (‘) to separate digits. So, you can write the same number as 9’524 without having an error, and it would also improve human comprehension when reading larger numbers in the C++ code.
Mathematically, integers are not unbounded, which means integers are infinite. But in C++, integers have limits because computers have a finite amount of memory. So, the maximum range of integer supported depends on the C++ compiler and the computer system. If, for example, we exceed the range of integer the C++ compiler can read, what happens? Try Code 2.4 on your 32-bit computer system and see what happens.
Code 2.4
#include <iostream>
int main () {
std::cout << - 9000000000 << ‘\n’;
}
According to the range of integer, a 32-bit can support, nine billion is too large for it, so it would either display an error or a wrong output. Whenever you get a warning in a code, it indicates that there is a potential problem, but it doesn’t stop the compiler from proceeding to give an executable program. So, as a programmer, you need to heed to warnings because the execution often produces a meaningless output.
Other programming languages as well have a limited range of vale because each number is stored in a fixed amount of memory. Meaning, if you want to save a larger number, then it would take up more storage space in the memory. To infinite a set of mathematical integers for C++, then you need an infinite amount of memory.
Variables and Assignment
Just like in algebra, variables represent numbers, and this same principle is applicable in C++ only that C++ variables can accept values other than numbers. Code 2.5 shows how C++ used variables to store an integer and also prints the value of that variable.
Code 2.5
#include <iostream>
int main () {
int a;
a=5;
std::cout << a << ‘\n’;
}
There are three statements in the main function in Code 2.5:
●
int a;
When writing a C++ code, all variables must be declared. And the int a;
is an example of a declaration statement. A declaration statement specifies what type of variables is being used. In Code 2.5, the int
indicates that the variable being used there is an integer and that the name of the integer is a
. So, we can read the code as the variable a
has type int
. C++ code supports other types of integers, some type of integer require more or less memory space for storing the variable’s value. A declaration statement allows the compiler to know if the developer is using the variable in the right way in the program. For example, the declaration statement can let us see if the integers are addable, just like in mathematics. In some other data types, addition is not possible, so it’s not allowed. The compiler also ensures the variables involved in a typical addition process are compatible with the addition rules. It would report an error if it is not compatible.
The compiler will also report an error is you attempt to use a variable without a declaration statement. The compiler can’t verify the variable’s proper usage, and it cannot deduce the storage requirement if it is not declared. When you use a declaration statement to declare a particular variable, you can’t redeclare that variable within the same context.
●
a=5;
This line is an assignment statement. You use an assignment statement to associate a value to a variable. The symbol =
in an assignment statement is key, and it’s also known as an assignment operator. In Code 2.5, the value 5 is being assigned to the variable a, meaning the value 5 will be stored in the memory the compiler reserved for the variable named a
.
●
std::cout << a << ‘\n’;
This statement simply means the current value of a
would be printed. Take note of the lack of quotation marks here; it’s very important. Consider Code 2.6 and Code 2.7:
Code 2.6
std::cout << a << ‘\n’;
Code 2.7
std::cout << “a” << ‘\n’;
In the statement in Code 2.6, it prints 5 as the values of the variable a, but in the statement in Code 2.7, it prints a
as the message containing the single letter a
.
In Code 2.5, the assignment operator (=) doesn’t mean the same thing as the equality operator in mathematics. The = operation in Math means that the expression on the left is equal to the expression on the right. But in C++, the = makes the variable on the left take the value of the expression on the right. It’s best to read a=5 as “a
is assigned the value of 5.” It's important we point this out, because the equality operation is symmetric in mathematics, meaning a=5 and 5=a, but in C++ it is not so.
Code 2.8
5=a
Code 2.8 means you’re trying to reassign a value to the literal integer value 5, and it’s impossible because 5 is always 5, and you can’t change it. Such a statement in a compiler would issue an error.
Code 2.9
error C2106: ‘=’ : left operand must be 1-value
Variables can also be reassigned to different values if there’s a need for it.
Code 2.10
#include <iostream>
int main () {
int a;
a=1;
std::cout << a << ‘\n’;
a=2;
std::cout << a << ‘\n’;
a=3;
std::cout <<a<< ‘\n’;
}
If you take a close look at Code 2.10, each print statement is identical, but after running the program, you’d get different results. Variables can also be given values the time you declare it. Take, for example, Code 2.11:
Code 2.11
#include <iostream>
int main () {
int a=5;
std::cout << a << ‘\n’;
}
If you notice, in this code, the declaration and assignment of the variable, a
is done in the same line statement and not two, as we have explained previously. The combination of declaration and assignment is called initialization. Likewise, C++ also support another syntax for initializing variables as should in Code 2.12:
Code 2.12
#include <iostream>
int main () {
int a {5};
std::cout << a << ‘\n’;
}
Code 2.12 is another way of combining declaration and assignment, but it is not common, especially for simple variables. Code 2.12 is necessary when you want to initialize a more complicated kind of variable called objects. We’d talk more about objects in later chapters of this book.
It is also possible to declare multiple variables of the same type in a single statement if desired. Consider the statement in Code 2.13:
Code 2.13
int a, b, c;
The statement in Code 2.13 declares three integer variables. Also consider the next statement that follows Code 2.13:
Code 2.14
int a = 1, b, c = 3;
In Code 2.14, b is undefined, and so the declaration can be split into multiple declaration statements:
Code 2.15
int a = 1;
int b;
int c = 5;
In Code 2.15, a multiple declaration statement, the type name int must appear in each statement.
Furthermore, a compiler maps a variable to a location in your computer’s memory. Take a look at Code 2.16:
Code 2.16
int x, y;
x = 1;
y = 2;
x = y;
y = 3;
Importantly, if we consider the statement x = y
, it doesn’t mean x
and y
are saved in the same memory location. It simply means that the same value that is in x
has been copied to y,
but they still have different memory locations. Going back to Code 2.16, x
was first declared as 1. Also, y
was later declared as 2 in its own memory location. When x
was declared the same value as y
(x = y
), the original value in x
was overwritten with the value in y
in that statement.
Identifiers
Unlike in mathematics, where variables are given one letter names like a, in programming, developers should use longer and more describes variable names as in user_name, sum,
and altitude
. When giving a variable a name, it must be related to the purpose of the program. A good variable name makes the program more readable by humans. Generally, programs contain so many variables, so a well-chosen variable name renders the program more understandable.
C++ programming has a very strict rule for naming variables. Naming variables is a perfect example of an identifier. Identifiers are words used to name things like variables. Identifiers can also name other things like classes and functions. Identifiers have the following forms:
●
It must contain at least one character.
●
Its first character must be an alphabetic letter, either upper or lower case or the underscore.
●
Its remaining characters can be either an alphabetic character (upper or lower case), an underscore, or a digit.
●
No other characters are permissible, including spaces.
●
Reserved words can’t be used as an identifier.
Here are some typical examples of acceptable and unacceptable identifiers.
●
The following are acceptable identifiers and can be used to name variables: a, a2, USB, E6400, and flow_22
●
The following are unacceptable identifiers: mini-port, last entry, 4all, #1, and class (class is a reserved word).
Some types of programming languages do not require you to declare a variable; it declares it automatically. Such programming languages assume the different types of variables based on how you use it in the different sections of the program. These types of languages are known as dynamically-typed languages. But the C++ programming language is statically-typed. And a statically-typed language is a type of programming language where the variable must be explicitly specified before a statement in a program can use it. The idea of having to declare all variables in C++ might seem trying at first, but it offers several advantages:
●
In a statically-typed language where variables must be declared, the compiler can easily catch the typographical errors that dynamically-typed language can’t detect.
●
Also, in statically-typed language where variables must be declared, the compiler can catch invalid operations that dynamically-types variables can’t detect. For example, you may want to declare a variable to be of type
int
, but you accidentally assign it a non-numerical value to the variable.
●
Ideally, because the C++ program requires you to declare variables, it makes you plan ahead and think more about the variables your program may need. The purpose of every variable is tied to its type, so you need to have a clear notion of the purpose of variables before declaring it.
●
Generally, statically-typed languages are more efficient than dynamically-typed languages.
In addition, C++ is case sensitive and so capitalization matters a great deal. For example, the word if
is reserved, but the words iF, IF, or If are not reserved and so you can use them to name variables. In the same manner, identifiers are case sensitive, and so, a variable called name
is different from a variable called Name
. Giving variables names that are distinguishable by capitalization is confusing.
Additional Integer Types
There are several other different types of integers supported by the C++ language. The type short int
, meaning short, represents integers that doesn’t occupy much bytes of memory like the int type. In retrospect, the smaller the memory space, the integer type occupies, the smaller the range of integer value. Standard C++ coding requires the short
type to be smaller than the int
type, as a matter of fact, they could represent the same set of integer values. There is also the long
int
type, which can also be written as just long
. In this case, the long
type can occupy more space than the int
type, allowing it to represent a much larger range of values. Standard C++ coding requires the long
type to be bigger than or equal to the int
type. Lastly, there is the long long
int
type also written as long long
for short. The long long
type may be larger than a long
. The relative ranges of values hold in C++ standards is as follows:
short int ≤ int ≤ long int ≤ long long int
Floating-Point Types
A lot of the computational task we do requires numbers, mostly numbers with fractional parts. For instance, a formula for mathematics that computes the area of a circle, given the circle’s radius, will involve the use of the value of π, which is approximately 3.14159. The C++ language supports such non-integer numbers, and they are known as floating-point numbers. The name comes from the ideology that in mathematical calculations, decimal points can float to various positions within the number to obtain significant digits. There are different types of floating-point numbers; the type double
and float
are the two most common.
The type double is often used, and they represent double-precision floating-point. It can also represent a wider range of values with more digits of precision. On the other hand, the float type represents single-precision floating-point values, which are less precise.
Constants
What are constants? Take, for example, the speed of light or Avogadro’s number; those are scientific constants. Constants are degree of precisions that have been calculated and measured, and they don’t vary. In C++, constants have the same meaning. They are declared just like the way we declare variables by adding the keyword const
. Once you declare a constant and initialize it, it can be used like a variable, expecting to reassign a constant. It is an error to have a constant on the left side of the assignment operator outside the declaration statement. For example:
PI = 9.8;
This would cause the compiler to run into an error and may display something like
error C3892: ‘PI’; you cannot assign a variable that is const
and it would fail obviously to compile the program. Because scientific constant doesn’t change, consider code 2.17 below:
Code 2.17
#include <iostream>
int main () {
const double c = 2.998e8, avogradros_number = 6.022e23;
std::cout <<“Speed of light = ” << c << ‘\n;
std::cout << “Avogadro’s number = ” << avogrados_number << ‘\n’;
}
Because it is not possible to assign a constant outside of a declaration statement, all constant has to be initialized where they are declared. So, generally, C++ developers have to express constant names in all capital letters. By doing so, it makes it possible for the human readers to distinguish between a variable and a constant easily.
Other Numeric Types
C++ also supports other numeric types which include:
-
long int: This typically provides integers that have a greater range than the int
type, and it has the long abbreviation. This form of numeric date guarantees to provide a range of integer’s values that are large at least up to the int
type. Take, for example, an integer with L suffix in 19L
has type long
. You can also use a lower case l as a suffix, but done use it too frequently because it’s hard for human readers to distinguish between lower case l and digit one 1.
-
short int: This typically provides you with an integer value that has a smaller range than the int type, and it’s abbreviated short
. This numeric form guarantees that the range of int
is bigger than the range of shorts
.
-
unsigned int: This numeric data type is typically restricted to nonnegative integers, and its abbreviated name is unsigned
. The unsigned
type is limited in nonnegative values, and it represents twice as many positive values as in the int
type.
-
long double: They can extend their precision and range of the double
type.
The C++ language specifies the minimum precision and ranges for all numeric data types, particularly the C++ compiler, which may exceed the specified minimum. So, C++ provides these varieties of numeric types for specialized purposes that are related to building highly efficient programs. Although we’d have very little use of these types because most of our examples will be making use of mainly the numeric types int
for integer, double
for an approximation of real number and unsigned
when nonnegative integer values are needed.
Characters
Characters abbreviated as char
is an example of a data type used to represent single characters – letters of the alphabet, either lower or upper case, punctuation, digit, and control characters. Most systems support the use of the American Standard Code for Information Interchange (ASCII) character sets. The ASCII standard can be represented in up to 128 different characters. In a C++ source code, the characters can be enclosed in single quotes, consider code 2.18 for more explanation.
Code 2.18
char ch = ‘B’;
The standard double quotes (“) are reserved for strings. Strings are composed of characters but don’t confuse strings and char; they are different. The following code would produce an error in a compiler.
Code 2.19
ch = “B”;
This error is due to the double quotes used to close the character, which is not a string. So, a string can’t be assigned to a character variable. C++ permits chars
to be saved as integer values. So, you can assign a numeric value to char variables and assign characters to numeric variables. In the statement
ch = 10;
the value 10 is the ASCII that is being assigned to the char
variable. So is we’re to print ch as in
ch = 10;
std::cout << ch;
The corresponding character B would be printed on the screen because ch’s declare type is char
and not int
or some other numeric type. Consider the example in code 2.20;
Code 2.20
#include <iostream>
int main () {
char ch1, ch2;
ch1 = 10;
ch2 = ‘B’;
std::cout <<ch1 << “,” << ch2 << “,” << ‘B; << ‘\n’;
}
Also, characters and integers can be assigned freely to each other, but the range of char
is smaller than the range of an int
. So, be careful when assigning an int
value to a char
value. Furthermore, some characters are non-printable. Below are some of the examples:
●
‘’\f’: This is the formfeed character
●
‘\θ’: This is the null character used in C strings
●
‘\t’: This is the tab character
●
‘\a’: This is the “alert” character used to cause a beep sound or tone in some systems
●
‘\b’: This is the backspace character
●
‘\r’: This is the carriage return character
●
‘\n’: This is the newline character
Enumerated Types
C++ also allows developers the ability to create a new and very simple type of list in any possible value of that type. These types of values are called enumeration type or enumerated type. The enumeration type is abbreviated as enum
. Check out the line below, it shows a simplified way to define an enumeration type:
Code 2.21
enum color {Violet, Blue, Green, Yellow, Orange, Red };
In the example above, the new type is name Color
, while the variable type of Color
can assume any type of color which appear on the list within the curly braces. It also follows with a semicolon after the closing curly brace. Sometimes the enumerated type can be in the format below:
Code 2.22
enum Color {
Violet,
Blue,
Green,
Yellow,
Orange,
Red
};
But in a complier, both code 2.21 and code 2.22 makes no difference.