Jimmy Neville

Home About Me Tutorials Workout Articles
C++ Intro, Variables

7/3/2019 - This tutorial explains variables and some other introductory topics. To follow along, you can either use a text editor/compiler of your choice, or you can use this website.

In the code block below, you'll see an outline for a basic C++ file. The #include <iostream> statement is an include directive which is a library containing input and output definitions, and the using namespace std; statement causes the names in iostream to be used in a standard way. At this point, the details about these statements aren't important; just know that at the top of every basic C++ program we'll need to include these lines of code. The main() function comes next, and the return statement at the end causes the function to terminate and return a value. You'll learn more about functions in a later tutorial; for now, just think of the main() function as the area we'll be typing our code.


// main.cpp

#include <iostream> using namespace std; int main() { return 0; }


Comments are how we document our program. There are two types of comments you'll use in C++:

// this is a single line comment

/* this is a
multi line
comment */

When commenting our code we want to clearly state what's happening, but not state something that our code has already stated. For example: int students = 31; //assign "31" to "students" is a comment stating something that our code is already clearly stating. Throughout this tutorial we'll mainly be using comments to help explain our examples.

Naming Variables

C++ is a case sensitive language; Int is not the same thing as int, and built-in types will always start with a lowercase letter. Also, variable names must start with a letter or underscore, and the characters that follow must be letters, digits or underscores. When naming variables, the first letter should always be lowercase; variables with an uppercase first letter are mainly used for classes, and we will talk about classes in a later tutorial. We also don't use underscores at the start of a variable name so that we can avoid collisions with names in other C++ libraries. Another way we avoid collisions is by avoiding variable names that other C++ libraries use; we call those variable names reserved keywords.

There are two common naming conventions for variables: camelCaseNames and underscore_names. You can use either, but pick one and stay consistent throughout your code. In this tutorial we'll be using camelCaseNames.

int num; //starts with a lowercase letter
int numOne; //camelcase naming convention
int num_one //underscore naming convention

int Num; //first letter capitalized
int _num; //starts with underscore
int money$; //contains a '$'
int public; "public" is a reserved word

One other thing to note is that whitespace is ignored by the compiler in C++. So, int num; and int     num; are the exact same statement.

Variable Declarations

Each line of code you see in the block above is called a "variable declaration," and every variable in a program must be declared before it can be used. It's also important to use meaningful names for variables. Suppose we're writing a program where we'll have several variables to keep track of a concession stand inventory:

int d = 4; //not good
int drinks = 4; //better

We want to be explicit here, but not too explicit: int numOfDrinksInInventory = 6; would be a little over the top. The longest variable name you want to use is about 3 words long: int numOfDrinks = 6; is perfect.

Variable Initialization

You'll notice in our example above that we've started assigning values to variables in our statements. This is called "variable initialization," and it's a good practice to initialize variables when you declare them. Think of a variable assignment as putting the value on the right into the variable on the left. Note that we can declare a variable and initialize the variable at the same time, or we can declare a variable and then assign it a value at a later point in the program:

int candyBars; //declaration
candyBars = 4; //initialization

int bagsOfChips = 4; //declaration & initialization                          

You could reassign the value of candyBars or bagsOfChips at a later point in the program, but you would not have to declare the variable again; you could just say candyBars = 8; or bagsOfChips = 10;

Variable Types

There are five main variable types in C++ that we'll cover in this tutorial: integers, doubles, characters, booleans and strings.


An integer is a whole number, and it usually takes up 4 bytes of memory. Well, the exact amount of memory each type takes up is dependent on the operating system. On a 32 bit machine ints take up 4 bytes, and on a 64 bit machine they take up 8 bytes. An int can store any value between -2,147,483,648 and 2,147,483,648. If we need a number larger than 2,147,483,648 we can use a type called "long int," and if we're using only positive numbers we can use "unsigned int" to get a value between 0 and 4,294,967,296. For most basic programs we don't have to worry about unsigned ints or long ints, but I mention them so that you're familiar with the terminology. We can also use mathematical operations on integers:

int num1 = 1 + 2; //num1 becomes 3
int num2 = 4 - 2; //num2 becomes 2
int num3 = num1 - num2; //num3 becomes 1
int num4 = 5 * 3; //num4 becomes 15
int num5 = 6 / 3; //num5 becomes 2
int num6 = 6 / 4; //num6 becomes 1

Remember PEMDAS from math class? C++ follows those same rules. We can put parenthesis around the part of the expression that we want evaluated first:

int num7 = 1 + 2 * 4; //num6 becomes 9
int num8 = (1 + 2) * 4; //num7 becomes 12

You may be looking at the num6 assignment above and thinking that there's a mistake: 6 / 4 is not 1! When using int division, the fraction gets cut off, and it will always round down to the nearest whole number. To calculate what's left over when we divide 6 by 4, we use the modulus (%) operator:

int num9 = 6 % 4; //num9 becomes 2
int num10 = 11 & 4; //num10 becomes 3

The modulus operator is useful in many circumstances. We'll use it when generating random numbers, and we'll also use it to find out if a number is a factor of another number: //if x % y == 0 then y is a factor of x


Doubles are similar to integers, but they also have a decimal point. Doubles have at least 14 digits of accuracy and take up 8 bytes of memory on a 32 bit machine. A double can store values between 10-308 and 10308. Something to remember is that if an expression contains a double, the result will be a double: 9 * 3.0 will equate to 27.0. Also note that division works intuitively with doubles, and if you store an int as a double it will be converted to a double:

double dub1 = 9; //gets stored as 9.0
double dub2 = 6.7 / 2.1; //dub2 becomes 3.19048


Characters take up 1 byte in memory and are assigned using single quotation marks: char letter1 = 'A';. Take a look at the ASCII Table to see what values you can store in a char, and also note that the value of a char is acutally just a small integer. If you look at the ASCII Table you can see that the letter 'A' is acutally just the number 65. So if you type: char letter1 = 65; an 'A' will be stored in letter1. You can also change the values of characters using expressions:

char letter2 = 'B'; //also the number 66
char letter3 = letter2 + 1; //letter3 becomes 'C' or 67
char letter4 = letter2 + 32; //letter3 becomes 'b' or 98


Booleans also take up 1 byte in memory and are true/false values. The default numeric value for false is 0, and the default value for true is 1: bool b1 = true; is the same as bool b1 = 1;. We can assign a bool to any int or double, and any value that's not 0 will be true. Both bool b2 = 99.3; and bool b2 = 43; will cause b2 to be true. It's also possbile to use bools in expressions:

int num11 = true + false + 8; //num11 becomes 9
int num12 = true + true + true; //num12 becomes 3


Strings are the last data type we'll cover in this tutorial. In order to use strings, we must declare #include <string> at the top of the file. Strings are assigned using double quotation marks, and they may contain spaces. We can also use the + operator to concatenate strings:

string firstName = "Jimmy "; //note the space at the end
string lastName = "Neville";
string fullName = firstName + lastName; //fullName becomes "Jimmy Neville" 

Safe/Unsafe Conversions

To to do a safe type conversion, there's important rules to follow. Unsafe conversions usually won't give an error or warning, but can cause major bugs in our program. Safe conversions are: bool to char, bool to int, bool to double, char to int, char to double, and int to double. Unsafe conversions are: double to int, double to char, double to bool, int to char, int to bool, and char to bool. If you look closely at the unsafe conversions, you'll see that the type on the left is larger than the type on the right; a 4 byte int will not fit into a 1 byte bool:

bool b1 = true;
int i1 = 9;

b1 = i1; //unsafe...int is larger than bool
i1 = b1; //safe...bool is smaller than int


A constant is a value that can't be changed. Initializeing a contant is as simple as adding const before the type: const int x = 5; //x can never be changed. If we try to reassign x at any point in our program we'll get an error. We can make any type a constant:

const int a = 5;
const double b = 6.0;
const char c = 'C';
const bool d = true;
const string e = "Hello World";

Basic Input and Output

We use cin for basic input, and we use cout for basic output:


// main.cpp

#include <iostream> using namespace std; int main() { int num = 0; cout << "Enter a number between 1 and 10: "; cin >> num; cout << "The number you entered is: " << num << endl; return 0; }

We use the insertion operator (<<) for cout, and the extraction operator (>>) for cin. To help remember which operator is for cin and which operator is for cout, we can think of the operators as arrows. The insertion operation is pointing "out" of the page (cout), and the extraction operator is pointing "in" to the page (cin). Note that cin is pronounced "see-in".

There are two ways you can insert a new line at the end of a cout statement. One way is with endl; like we used in the example above, and another way is by using "\n":


// main.cpp

#include <iostream> using namespace std; int main() { int num = 0; cout << "Hello!\n"; cout << "C++ is a" << endl; cout << "cool language!" << "\n"; return 0; }

You can see that "\n" must be used in quotation marks. The difference in the two is that endl; flushes the output buffer, and "\n" does not flush the output buffer.

Note that cin will ignore whitespace before anything you type and will terminate when it reaches whitespace:


// main.cpp

#include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter your first name: "; cin >> name; //entering "Jimmy" cout << "You entered " << name << endl; //output will be: "You entered Jimmy" return 0; }

You could also enter "     Jimmy" into the cin statement and the results would be the same because the preceding whitespace is ignored. Let's look at another example:


// main.cpp

#include <iostream> #include <string> using namespace std; int main() { string name2; cout << "Enter your full name: "; cin >> name2; //entering "Jimmy Neville" cout << "You entered " << name2 << endl; //output will still be: "You entered Jimmy" return 0; }

The input stream will only read the first name because it terminates at whitespace. If we want to read the full name we need to use getline():


// main.cpp

#include <iostream> #include <string> using namespace std; int main() { string name2; cout << "Enter your full name: "; getline(cin, name2); //entering "Jimmy Neville" cout << "You entered " << name2 << endl; //output will now be: "You entered Jimmy Neville" return 0; }


You have reached the end of the first tutorial! We'll learn a lot more about the data types we've covered in this tutorial in the tutorials to follow as we explore new topics.



Programming Principles and Practices Using C++ by Bjarne Stroustrup

Problem Solving With C++ 9th Edition by Walter Savitch

Back to homepage