Contents

Types

When programming, we usually need to keep track of various values throughout the life of the program. For example, if we are programming a calculator program, we need to keep track of the operator, the operand, and the result. Values come in various types, such as whole numbers, decimals, individual characters, or strings of characters. In this section we will discuss the specifics of the types allowed in C++.

\ref supplies a list of most the C++ types we'll use, along with examples.

C++ types
TypeDescriptionExamples
intWhole integers, up to ±327675, 10, -2039
longWhole integers up to ±2147483647-5, 10000000
floatFloating point (decimals)4.5, 3, 9.139482
doubleLonger decimals39929391.9103
charSingle character (a whole integer between 0–255)'a', 'Z', 127
stringA string of characters"Hello there!"
boolBoolean (true or false)true, false

The key with types is to choose the one that best fits your situation. For example, if you are trying to keep track of a person's age, then an int is the best fit, since the age won't go outside of the range, and you don't need a decimal. If you need to keep track of a name, then you should use a string, since names are a sequence of characters. An initial or individual symbol (like '*') is best represented using a char. Use a bool when you need to keep track of a binary state, e.g., whether a game is over or not.

(Back to top)

Variables

When we want to store a value that we don't know at the beginning of our program (because we want to read it in from the user or base it on a computation), or if that value might change throughout the course of a program, we can store it in a variable. A variable stores values that can vary. The value of a variable can be set over and over again. There are several parts to using variables: declaring, initializing, accessing, and re-assigning. We talk about these below, as well as scope.

Declaring variables

In C++, we must declare variables by supplying the type followed by the name of our variable (the name is called an identifier). This must be done before we can ever use a variable or assign a value to it. For example, to declare a variable to hold the value of an age, we can do the following:

Here are a few more examples:

There are rules about identifiers, however. For instance, they may not start with any character other than a-z, A-Z, and _. In addition, no reserved C++ keywords can be used, which include the following:

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

While the C++ compiler doesn't really care what you name your variables, you should. The style I recommend is to avoid all but the most common abbreviations and use camelCasing when your names have multiple words. For example, if I have a variable for my brother's age, I would name it: brothersAge, rather than broAge, brother_age, or, worst of all, ba. There are certain situations when a single letter identifier is okay, but in general, you should avoid it. Identifiers that are easy to read and understand improve code comprehension. That's good for you, for me, and for anyone else who ends up looking at your code.

Assigning values to variables

The next step is to assign the first value to a variable. We call this initializing the variable. Any assignment to a variable thereafter is referred to as a re-assignment.

In C++, we use the = sign to mean "gets", or "is assigned". The variable that is getting the value is on the left, and the value that is being gotten is on the right. For example, age = 5; will assign the value 5 to the variable age. We read this "age gets the value 5" or "age is set to 5". It is quite common to think of = the way it is used in math—it's different in programming! In programming, it's an assignment operator, not a test of equality. The things on the left always gets the value of whatever is on the right.

Initialization can take place at the same time a variable is declared, or after the declaration. For example, here's an example of separating the two steps:

And here's the version where they happen at the same time:

Here are the assignments for the variables we declared in the previous subsection:

That right hand side can also be a variable or complex expression. For instance, if we have another variable, say, brothersAge, and I want to set age to the value stored in brothersAge, then I could do that with this assignment: age = brothersAge;. This assumes, of course, that both variables have been declared and that brothersAge has been initialized. E.g.,:

At the end, the value stored in age is 10 and the value stored in brothersAge is 11. Why? In memory, the assignment operator copies the value stored in the variable on the right and stores it in the variable on the left. They are not being linked—the data is being copied.

Complex expressions

As mentioned above, we can also have complex expressions on the right. Technically, 5 and brothersAge are expressions, albeit simple ones. An example of a more complex expression would be a mathematical one, e.g.,:

Here we've initialized brothersAge to 11. We then assign brothersAge-1 to age, which is 10. So the final value of age is 10. For numerics, like int, long, float, and double, we can use a series of operators between them: +, -, /, *.

Numeric variables can also use short cuts for reassigning their values, as shown in the table below:

Numeric expression operators
OperatorDescriptionExampleEquivalent to
+=Increments the variable on the left by the value on the rightage += 10;age = age + 10;
-=Decrements the variable on the left by the value on the rightage -= 10;age = age - 10;
*=Multiplies and updates the variable on the left by the value on the rightage *= 10;age = age * 10;
/=Divides and updates the variable on the left by the value on the rightage /= 10;age = age / 10;
++Increments the variable on the left by oneage++;age = age + 1;
--Decrements the variable on the left by oneage--;age = age - 1;

Whole number integers (e.g., of type int and long) can make use of the modulo operator, represented as %. Modulo yields the remained after dividing the value to its right by the value on the left. E.g., 10 % 7 is 3, because 7 goes into 10 once, with a remainder of 3. So the assignment int age = 10 % 7; will assign 3 to the variable age.

Scope

Where variables are declared also matters. Variables must be declared in the scope in which they are used. Until we learn about functions, main will be our primary scope. So, we should declare all the variables we need at the top of the main function:

What if we did the following?

The variable age has a global scope, because it can be accessed everywhere—in every single function in your code. Global scope should almost always be avoided with variables. There is no situation in this class where you should declare a variable in the global scope. The primary reason for this is that you have no control over what functions modify the value stored in global variables. There are better ways to pass values within your code.

(Back to top)

Constants

Variables are perfect when we have values that might vary during the lifetime of the program. Sometime, however, we need a value that we know will never change. For example, π (3.14...) or minimum drinking age. C++ gives us a special keyword to stick in front of our declaration to say "this value will never change": const. This is then followed by the type, the identifier, and the initialization. Unlike variables, constants must be initialized when they are declared. Here's an example of declaring a constant for π and the minimum drinking age:

Notice that constants' names are all upper case, and there spaces are represented as underscores. This is the convention we will use for constants. It makes it extremely easy to tell what values are constants later on in the program.

Also unlike variable, the most appropriate place for constants are in the global space. So add them to the header of your C++ programs. One of our reasons for not wanting variables to be global is that we loose control over what code can reassign values to global variables. However, since constants cannot be changed, we don't have that worry. More over, constants are always hard coded, whereas variables are usually read in from a user, file, or are the result of a calculation (our early examples are an exception that this generality). Because constants are hard coded, having them at the top of the program makes them easy for a programmer to update as needed (e.g., if we needed more precision for PI, or if the minimum drinking age changed). Here's an example of a program with our constants declared:

(Back to top)