You are on page 1of 63

INTRODUCTION TO PROGRAMMING LANGUAGES

Modern computers are incredibly fast, and getting faster all the time. Yet with this speed comes some significant
constraints. Computers only natively understand a very limited set of instructions, and must be told exactly what to do. A
program (also commonly called an application or software) is a set of instructions that tells the computer what to do. The
physical computer machinery that executes the instructions is the hardware.

Machine Language
A computers CPU is incapable of speaking C++. The very limited set of instructions that a CPU natively
understands is called machine code (or machine language or an instruction set). How these instructions are
organized is beyond the scope of this introduction, but it is interesting to note two things. First, each instruction is
composed of a number of binary digits, each of which can only be a 0 or a 1. These binary numbers are often
called bits (short for binary digit). For example, the MIPS architecture instruction set always has instructions that
are 32 bits long. Other architectures (such as the x86, which you are likely using) have instructions that can be a
variable length.
Here is an example x86 machine language instruction: 10110000 01100001
Second, each set of binary digits is translated by the CPU into an instruction that tells it to do a very specific job,
such as compare these two numbers, or put this number in that memory location. Different types of CPUs will
typically have different instruction sets, so instructions that would run on a Pentium 4 would not run on a
Macintosh PowerPC based computer. Back when computers were first invented, programmers had to write
programs directly in machine language, which was a very difficult and time consuming thing to do.
Assembly Language
Because machine language is so hard to program with, assembly language was invented. In an assembly language,
each instruction is identified by a short name (rather than a set of bits), and variables can be identified by names
rather than numbers. This makes them much easier to read and write. However, the CPU can not understand
assembly language directly. Instead, it must be translated into machine language by using an assembler. Assembly
languages tend to be very fast, and assembly is still used today when speed is critical. However, the reason
assembly language is so fast is because assembly language is tailored to a particular CPU. Assembly programs
written for one CPU will not run on another CPU. Furthermore, assembly languages still require a lot of
instructions to do even simple tasks, and are not very human readable.
Here is the same instruction as above in assembly language: mov al, 061h
High-level Languages
To address these concerns, high-level programming languages were developed. C, C++, Pascal, Java, Javascript,
and Perl, are all high level languages. High level languages allow the programmer to write programs without
having to be as concerned about what kind of computer the program is being run on. Programs written in high
level languages must be translated into a form that the CPU can understand before they can be executed. There are
two primary ways this is done: compiling and interpreting.

A compiler is a program that reads code and produces a stand-alone executable program that the CPU can
understand directly. Once your code has been turned into an executable, you do not need the compiler to run the
program. Although it may intuitively seem like high-level languages would be significantly less efficient than
assembly languages, modern compilers do an excellent job of converting high-level languages into fast
executables. Sometimes, they even do a better job than human coders can do in assembly language!
Here is a simplified representation of the compiling process:

An interpreter is a program that directly executes your code without compiling it into machine code first.
Interpreters tend to be more flexible, but are less efficient when running programs because the interpreting process
needs to be done every time the program is run. This means the interpreter is needed every time the program is run.
Here is a simplified representation of the interpretation process:

Any language can be compiled or interpreted, however, traditionally languages like C, C++, and Pascal are
typically compiled, whereas scripting languages like Perl and Javascript are interpreted. Some languages, like
Java, use a mix of the two.
High level languages have several desirable properties.
First, high level languages are much easier to read and write.
Here is the same instruction as above in C/C++: a = 97;
Second, they require less instructions to perform the same task as lower level languages. In C++ you can do
something like a = b * 2 + 5; in one line. In assembly language, this would take 5 or 6 different instructions.
Third, you dont have to concern yourself with details such as loading variables into CPU registers. The compiler
or interpreter takes care of all those details for you.
And fourth, they are portable to different architectures, with one major exception, which we will discuss in a
moment.

The exception to portability is that many platforms, such as Microsoft Windows, contain platform-specific
functions that you can use in your code. These can make it much easier to write a program for a specific platform,
but at the expense of portability. In these tutorials, we will explicitly point out whenever we show you anything
that is platform specific.

INTRODUCTION TO C/C++
Before C++, there was C
The C language was developed in 1972 by Dennis Ritchie at Bell Telephone laboratories, primarily as a systems
programming language. That is, a language to write operating systems with. Richies primary goals were to
produce a minimalistic language that was easy to compile, allowed efficient access to memory, produced efficient
code, and did not need extensive run-time support. Thus, for a high-level language, it was designed to be fairly
low-level, while still encouraging platform-independent programming.
C ended up being so efficient and flexible that in 1973, Ritchie and Ken Thompson rewrote most of the UNIX
operating system using C. Many previous operating systems had been written in assembly. Unlike assembly,
which ties a program to a specific CPU, Cs excellent portability allowed UNIX to be recompiled on many
different types of computers, speeding its adoption. C and Unix had their fortunes tied together, and Cs popularity
was in part tied to the success of UNIX as an operating system.
In 1978, Brian Kernighan and Dennis Ritchie published a book called The C Programming Language. This
book, which was commonly known as K&R (after the authors last names), provided an informal specification for
the language and became a de facto standard. When maximum portability was needed, programmers would stick to
the recommendations in K&R, because most compilers at the time were implemented to K&R standards.
In 1983, the American National Standards Institute (ANSI) formed a committee to establish a formal standard for
C. In 1989 (committees take forever to do anything), they finished, and released the C89 standard, more
commonly known as ANSI C. In 1990 the International Organization for Standardization adopted ANSI C (with a
few minor modifications). This version of C became known as C90. Compilers eventually became ANSI C/C90
compliant, and programs desiring maximum portability were coded to this standard.
In 1999, the ANSI committee released a new version of C called C99. It adopted many features which had already
made their way into compilers as extensions, or had been implemented in C++.
C++
C++ (pronounced see plus plus) was developed by Bjarne Stroustrup at Bell Labs as an extension to C, starting in
1979. C++ adds many new features to the C language, and is perhaps best thought of as a superset of C, though
this is not strictly true as C99 introduced a few features that do not exist in C++. C++s claim to fame results
primarily from the fact that it is an object-oriented language. As for what an object is and how it differs from
traditional programming methods, well, well cover that in chapter 8 (Basic object-oriented programming).
C++ was ratified in 1998 by the ISO committee, and again in 2003 (called C++03). Two updates to the C++
language (C++11 and C++14, ratified in 2011 and 2014 accordingly) have been made since then, adding additional
functionality to the language. Relevant features from both of these updates will be discussed in these tutorials.
C and C++s philosophy

The underlying design philosophy of C and C++ can be summed up as trust the programmer -- which is both
wonderful, because the compiler will not stand in your way if you try to do something unorthodox that makes
sense, but also dangerous, because the compiler will not stand in your way if you try to do something that could
produce unexpected results. That is one of the primary reasons why knowing what you shouldnt do in C/C++ is
almost as important as knowing what you should do -- because there are quite a few pitfalls that new programmers
are likely to fall into if caught unaware.

INTRODUCTION TO DEVELOPMENT
Before we can write and execute our first program, we need to understand in more detail how C++ programs get
developed. Here is a graphic outlining a simplistic approach:

Step 1: Define the problem that you would like to solve.


This is the what step, where you figure out what you are going to solve. Coming up with the initial idea for what
you would like to program can be the easiest step, or the hardest. But conceptually, it is the simplest. All you need
is an idea that can be well defined, and youre ready for the next step.
Here are a few examples:

I want to write a program that will allow me to enter numbers, then calculates the average.
I want to write a program that generates a 2d maze and lets the user navigate through it.
I want to write a program that reads in a file of stock prices and predicts whether the stock will go up or
down.

Step 2: Determine how you are going to solve the problem.


This is the how step, where you determine how you are going to solve the problem you came up with in step 1.
It is also the step that is most neglected in software development. The crux of the issue is that there are many ways
to solve a problem -- however, some of these solutions are good and some of them are bad. Too often, a

programmer will get an idea, sit down, and immediately start coding a solution. This often generates a solution that
falls into the bad category.
Typically, good solutions have the following characteristics:

They are straightforward.


They are well documented (especially any assumptions being made).
They are built modularly, so parts can be reused or changed later without impacting other parts of the
program.
They are robust, and can recover or give useful error messages when something unexpected happens.

When you sit down and start coding right away, youre typically thinking I want to do _this_, so you implement
the solution that gets you there the fastest. This can lead to programs that are fragile, hard to change or extend, or
have lots of bugs.
Studies have shown that only 20% of a programmers time is actually spent writing the initial program. The other
80% is spent debugging (fixing errors) or maintaining (adding features to) a program. Consequently, its worth
your time to spend a little extra time up front before you start coding thinking about the best way to tackle a
problem, what assumptions you are making, and how you might plan for the future, in order to save yourself a lot
of time and trouble down the road.
Well talk more about how to effectively design solutions to problems in a future lesson.
Step 3: Write the program
In order to write the program, we need two things: First we need knowledge of a programming language -- thats
what these tutorials are for! Second, we need an editor. Its possible to write a program using any editor you want,
even something as simple as Windows notepad or Unixs vi or pico. However, we strongly urge you to use an
editor that is designed for coding. Dont worry if you dont have one yet. Well cover how to install one soon.
A typical editor designed for coding has a few features that make programming much easier, including:
1) Line numbering. Line numbering is useful when the compiler gives us an error. A typical compiler error will
state error, line 64. Without an editor that shows line numbers, finding line 64 can be a real hassle.
2) Syntax highlighting and coloring. Syntax highlighting and coloring changes the color of various parts of your
program to make it easier to see the overall structure of your program.
3) An unambiguous font. Non-programming fonts often make it hard to distinguish between the number 0 and the
letter O, or between the number 1, the letter l (lower case L), and the letter I (upper case i). A good programming
font will differentiate these symbols in order to ensure one isnt accidentally used in place of the other.
Your C++ programs should be called name.cpp, where name is replaced with the name of your program. The .cpp
extension tells the compiler (and you) that this is a C++ source code file that contains C++ instructions. Note that
some people use the extension .cc instead of .cpp, but we recommend you use .cpp.

Also note that many complex C++ programs have multiple .cpp files. Although most of the programs you will be
creating initially will only have a single .cpp file, it is possible to write single programs that have tens if not
hundreds of individual .cpp files.
Step 4: Compiling
In order to compile a program, we need a program called a compiler. The job of the compiler is twofold:
1) To check your program and make sure it follows the rules of the C++ language. If it does not, the compiler will
give you an error to help pinpoint what needs fixing.
2) To convert each file of source code into a machine language file called an object file. Object files are typically
named name.o or name.obj, where name is the same name as the .cpp file it was produced from. If your program
had 5 .cpp files, the compiler would generate 5 object files.

For illustrative purposes only, most Linux and Mac OS X systems come with a C++ compiler called g++. To use
g++ to compile a file from the command line, we would do this:
g++ -c file1.cpp file2.cpp file3.cpp

This would create file1.o, file2.o, and file3.o. The -c means compile only, which tells g++ to just produce .o
(object) files.
Other compilers are available for Linux, Windows, and just about every other system. We will discuss installing a
compiler in the next section, so there is no need to do so now.
For complex projects, some development environments use a makefile, which is a file that tells the compiler
which files to compile. Makefiles are an advanced topic, and entire books have been written about them.
Fortunately, you dont need to worry about them, so we will not discuss them here.
Step 5: Linking
Linking is the process of taking all the object files generated by the compiler and combining them into a single
executable program that you can run. This is done by a program called the linker.

In addition to the object files for a program, the linker also includes files from the C++ standard library (or any
other precompiled libraries youre using, such as graphics or sound libraries). The C++ language itself is fairly
small and simple. However, it comes with a large library of optional components that may be utilized by your
programs, and these components live in the C++ standard library. For example, if you wanted to output something
to the screen, your program would include a special command to tell the compiler that you wanted to use the I/O
(input/output) routines from the C++ standard library.
Once the linker is finished linking all the object files (assuming all goes well), you will have an executable file.
Again, for illustrative purposes, to link the .o files we created above on a Linux or OS X machine, we can again
use g++:
g++ -o prog file1.o file2.o file3.o

The -o tells g++ that we want an executable file named prog that is built from file1.o, file2.o, and file3.o
The compile and link steps can be combined together if desired:
g++ -o prog file1.cpp file2.cpp file3.cpp

Which will combine the compile and link steps together and directly produce an executable file named prog.
Step 6: Testing and Debugging
This is the fun part (hopefully)! You are able to run your executable and see whether it produces the output you
were expecting. If not, then its time for some debugging. We will discuss debugging in more detail soon.
Note that steps 3, 4, 5, and 6 all involve software. While you can use separate programs for each of these
functions, a software package known as an integrated development environment (IDE) bundles and integrates
all of these features together. With a typical IDE, you get a code editor that does line numbering and syntax
highlighting. You get a compiler and a linker. The IDE will automatically generate the parameters necessary to
compile and link your program into an executable, even if it includes multiple files. And when you need to debug

your program, you can use the integrated debugger. Furthermore, IDEs typically bundle a number of other helpful
editing features, such as integrated help, name completion, hierarchy browsers, and sometimes a version control
system.

INSTALLING AN INTEGRATED DEVELOPMENT


ENVIRONMENT (IDE)
As mentioned in the previous section, an Integrated Development Environment (IDE) contains all of the things
you need to develop, compile, link, and debug your programs. So lets install one.
The obvious question is, which one?. Keep in mind that you can install multiple IDEs, so there is no wrong
decision here. During the course of these tutorials, we will be showing you some of the nice features of your IDE,
such as how to do integrated debugging. All of our examples will be done using both Microsofts Visual C++ (for
Windows), and Code::Blocks (for Linux or Windows). Thus we highly recommend you pick one of these.
However, if you would like to try a different IDE, you are free to do so. The concepts we show you will work for
any IDE -- however, different IDEs use different keymappings and different setups, and you may have to do a bit
of searching to find the equivalent of what we show you.
Windows IDEs
If you are developing on a Windows machine (as most of you are), then you have two choices:
1) If disk space and/or download size are not a constraint, then we recommend Visual Studio Community 2015.
Note that Visual Studio 2015 does not come with the C++ compiler installed by default, so youll need to do a
Custom installation and choose Programming Languages -> Visual C++. You can also uncheck the Windows
and Web Development checkbox if you want to save some room, as you wont need those for this tutorial series.

2) If disk space and/or download size are a challenge, then we recommend Microsofts free Visual Studio Express
2013 for Windows Desktop. When asked, choose wdexpress_full.exe and run it.
The installer that you download off of Microsofts web page is actually a downloader. When you run it, it will
download the actual IDE from Microsoft and install it.
Note: This tutorial was originally written when Microsoft was distributing the 2005 version of Visual C++.
Consequently, most references and screenshots are targeted to that version. Running any later versions (such as
2008, 2010, 2013, 2015, etc) are fine, however, your screens may look slightly different.

Linux or Windows IDEs


If you are developing on Linux (or you are developing on Windows but want to write programs that you can easily
port to Linux), we recommend Code::Blocks. Code::Blocks is a free, open source, cross-platform IDE that will run
on both Linux and Windows.
Windows users: make sure to get the version with MinGW bundled.
With Code::Blocks, C++11/C++14 functionality may be disabled by default. Youll definitely want to check and
turn it on. First, go to Settings->Compiler:

Then check the box marked Have g++ follow the C++11 ISO C++ language standard [-std=c++11]:

Note: If Have g++ follow the C++14 ISO C++ language standard [-std=c++14] exists for your version of
Code::Blocks, use that instead.
Alternately, some people prefer to use Bloodsheds Dev-C++, which also runs on both Windows and Linux.
Mac OSX IDEs
Mac users can use Xcode if it is available to you, or Eclipse. Eclipse is not set up to use C++ by default, and you
will need to install the optional C++ components.
Can I use a web-based compiler?

Yes, for some things. While your IDE is downloading (or if youre not sure you want to commit to installing one
yet), you can continue this tutorial using a web-based compiler, such as the one at TutorialsPoint.
Web-based compilers are fine for dabbling and simple exercises. However, they are generally quite limited in
functionality -- many wont allow you to save projects, create executables, or effectively debug your programs.
Youll want to migrate to a full IDE when you can.
Moving on
Once your IDE is installed (which is one of the hardest things this tutorial will ask you to do), or if youre
temporarily proceeding with a web-based compiler, you are ready to write your first program!

COMPILING YOUR FIRST PROGRAM


Before we can write our first program (which we will do very soon), we need to know a few things about
development environments.
First, although our programs will be written inside .cpp files, the .cpp files themselves will be added to a project.
The project stores the names of all the code files we want to compile, and also saves various IDE settings. Every
time we reopen the project, it will restore the state of the IDE to where we left off. When we choose to compile our
program, the project tells the compiler and linker which files to compile and link. It is worth noting that project
files for one IDE will not work in another IDE. You will need to create a new project for each program you write
(or overwrite an old one).
Second, there are different kinds of projects. When you create a new project, you will have to pick a project type.
All of the projects that we will create in this tutorial will be console projects. A console project means that we are
going to create programs that can be run from the dos or linux command-line. By default, console applications
have no graphical user interface (GUI) and are compiled into stand-alone executable files. This is perfect for
learning C++, because it keeps the complexity to a minimum.
Third, when you create a new project for your program, many IDEs will automatically add your project to a
workspace or a solution. A workspace or solution is a container that can hold one or more related projects.
Although you can add multiple projects to a single solution, we recommend creating a new workspace or solution
for each program. Its simpler and theres less chance of something going wrong.
Traditionally, the first program programmers write in a new language is the infamous hello world program, and we
arent going to deprive you of that experience! Youll thank us later. Maybe.
A quick note about examples containing code
Starting with this lesson, you will see many examples of C++ code presented. Most of these examples will look
something like this:
1 #include <iostream>
2
3 int main()
4{
5 std::cout << "Hello world!" << std::endl;
6 return 0;
7}
If you select the code from these examples with your mouse and then copy/paste it into your IDE, you may also
get the line numbers (depending on how you made the selection). If so, youll need to remove these manually.
If youre using the Visual Studio IDE

Although the following section was written using Visual Studio 2005, it essentially works the same for all versions
of Visual Studio.
To create a new project in Visual Studio, go to the File menu, and select New -> Project. A dialog box will pop up
that looks like this:

First, make sure Visual C++ is selected on the left side.


Second, underneath Visual C++, select the Win32 project type, and Win32 Console Application will
automatically be selected for you. In the Name field, you will enter the name of your program. Type in
HelloWorld. In the Location field, pick a directory that you would like your project to be placed into. We
recommend you place them in a subdirectory off of your C drive, such as C:\VC2005Projects. Click OK, and
then Finish.
On the left side, in the Solution Explorer, Visual Studio has created a number of files for you, including stdafx.h,
HelloWorld.cpp, and stdafx.cpp.

In the text editor, you will see that VC2005 has already created some code for you. Select and delete all of the
code, and type/copy the following into your compiler:
1 #include "stdafx.h"
2 #include <iostream>
3
4 int main()
5{
6 std::cout << "Hello world!" << std::endl;
7 return 0;
8}
What you end up with should look like this:

To compile your program, either press F7 or go to the Build menu and choose Build Solution. If all goes well,
you should see the following appear in the Output window:

This means your compile was successful!


To run your compiled program, press ctrl-F5, or go the Debug menu and choose Start Without Debugging. You
will see the following:

That is the result of your program!


Note: If you see the console window (black box) without any text, your anti-virus may be interfering. Try turning
your anti-virus off temporarily and try again.
Important note to Visual Studio users: Visual studio programs should ALWAYS begin with the following line:
1 #include "stdafx.h"
Otherwise you will receive a compiler warning, such as c:testtest.cpp(21) : fatal error C1010:
unexpected end of file while looking for precompiled header directive

Alternately, you can turn off precompiled headers. However, using precompiled headers will make your program
compile much faster, so we recommend leaving them on unless you are developing a cross-platform program.
The example programs we show you throughout the tutorial will not include this line, because it is specific to your
compiler.
If youre using the Code::Blocks IDE
To create a new project, go to the File menu, and select New Project. A dialog box will pop up that looks
something like this:

Select Console Application and press the Go button.


This should pop up a wizard:

On the next page, select C++ as your language. Click Next.

Next, youll be asked to name your project and choose a location. For your project title, set a name (such as
HelloWorld). In the Project Title field, you will enter the name of your program. Type in HelloWorld. In the
Folder to create project in field, pick a directory that you would like your project to be placed into. We
recommend you place them in a subdirectory off of your C drive, such as C:\CBProjects. Click Next.

On the next screen, Code::Blocks asks you what compiler you want to use, and what configurations you want.
Dont touch anything here, just hit Finish.

Now youve created your project, and should see your project under the default workspace:

Open the tree under Console Application, open Sources, and double click on main.cpp. You will see that the
hello world program has already been written for you!
To build your project, press ctrl-F9, or go to the Build menu and choose Build. If all goes well, you should see
the following appear in the Build log window:

This means your compile was successful!


To run your compiled program, press ctrl-F10, or go the Build menu and choose Run. You will see something
similar to the following:

That is the result of your program!

If youre using a command-line based compiler


Paste the following into a text file named HelloWorld.cpp:
1 #include <iostream>
2
3 int main()
4{
5 std::cout << "Hello world!" << std::endl;
6 return 0;
7}
From the command line, type:
g++ -o HelloWorld HelloWorld.cpp

This will compile and link HelloWorld.cpp. To run it, type:


HelloWorld

(or possibly ./HelloWorld), and you will see the output of your program.

If youre using a web-based compiler temporarily


Paste the following into the input form:
1 #include <iostream>
2
3 int main()
4{
5 std::cout << "Hello world!" << std::endl;
6 return 0;
7}
and then press Run. You should see your output below the form.
Once you install a full IDE, youll want to return to this lesson again to learn how to create a project in your IDE.
If youre using other IDEs
You will have to figure out how to do the following on your own:
1) Create a console project
2) Add a .cpp file to the project (if necessary)
3) Paste the following code into the file:

1 #include <iostream>
2
3 int main()
4{
5 std::cout << "Hello world!" << std::endl;
6 return 0;
7}
4) Compile the project
5) Run the project
If compiling fails (aka. Oh god something went wrong!)
Its okay, take a deep breath. We can probably fix it.
First, check to ensure that youve typed the code in correctly, with no typos or misspellings (also, make sure
youre not including line numbers in your code). The compilers error message may give you a clue as to where or
what the problem is.
Second, check lesson 0.7 -- A few common C++ problems, as many common problems are addressed there
(including the COFF error that many of you are encountering).
If that fails, try searching for your error message on Google. Its likely someone else has encountered this before
and figured out how to fix it.
If you are using a much older C++ compiler, the compiler may give an error about not understanding how to
include iostream. If this is the case, try the following program instead:
1 #include <iostream.h>
2
3 int main()
4{
5 cout << "Hello world!" << endl;
6 return 0;
7}
In this case, you should upgrade your compiler to something more compliant with recent standards.
If your program runs but the window closes immediately
This is an issue with some compilers, such as Bloodsheds Dev-C++. We present a solution to this problem in
section A few common C++ problems.

BUILD CONFIGURATIONS
A build configuration (also called a build target) is a collection of project settings that determines how your IDE
will build your project. The build configuration typically includes things like what the executable will be named,
what directory the executable will be output in, what directories the IDE will look in for other code and header
files, whether to keep or exclude debugging information, and how highly to have the compiler optimize your
program. Generally, you will want to leave the settings at their default values unless you have a specific reason to
change something.
When you create a new project in your IDE, the IDE will generally set up two different build configurations for
you: a release configuration, and a debug configuration.
The debug configuration is designed to help you debug your program, and is generally the one you will use when
developing your programs. This configuration turns off all optimizations, and includes debugging information,
which makes your programs larger and slower, but much easier to debug. The debug configuration is usually
selected as the active configuration by default.
The release configuration is designed to be used when releasing your program to the public. This version is
typically optimized for size and performance, and doesnt contain the extra debugging information.
For example, when the Hello World program from the previous lesson was built using Visual Studio 2013, the
executable produced in the debug configuration was 65kb, whereas the executable built in the release version was
12kb.
Switching between debug and release in Visual Studio
There are multiple ways to switch between debug and release in Visual Studio. The easiest way is to find the
Solution Configurations dropdown in the Standard Toolbar Options menu:

It should be set to Debug or Release. You can change which one youre using by selecting it in the dropdown.
You can also access the configuration manager dialog, by selecting Build->Configuration Manager, and change
the Active solution configuration.

Switching between debug and release in Code::Blocks


In Code::Blocks, you should see a toolbar item called Build Target:

It can be set to debug or release in the dropdown.


Summary
The build configuration holds the settings for different versions of your project. You generally wont need to touch
these settings, but you may want to switch between debug and release.
Rule: Use the debug configuration when developing your programs. When youre ready to release your executable
to others, build it using the release configuration.

A FEW COMMON C++ PROBLEMS


In this section, well address some of the common issues that new programmers seem to run across with fairly high
probability. This is not meant to be a comprehensive list of compilation or execution problems, but rather a
pragmatic list of solutions to very basic issues. If you have any suggestions for other issues that might be added to
this list, post them in the comments section below.
Problem 1: When executing a program from the IDE, the console window blinks and then closes immediately.

Answer 1: Some compilers (eg. Bloodsheds Dev C++) dont automatically pause the console screen after the
program has finished executing. If this is the case with your compiler, the following two steps will fix your
problem:
First, add the following line near the top of your program:
1 #include <iostream>

Second, add the following code at the end of the main() function (right before the return statement):
1 std::cin.clear(); // reset any error flags
2 std::cin.ignore(32767, '\n'); // ignore any characters in the input buffer until we find an enter character
3 std::cin.get(); // get one more char from the user

This will cause your program to wait for you to press a key before continuing, which will give you time to
examine your programs output before your compiler closes the console window.
Other solutions, such as the commonly suggested system("pause") solution may only work on certain operating
systems and should be avoided.
Note: Visual Studio will not pause at the end of a console application if it is run with debugging (Debug Menu>Start Debugging). If you want it to pause, you can either use the code solution above, or run your program
without debugging (Debug Menu->Start Without Debugging).
Problem 2: When compiling with Microsoft Visual C++, you get the following error:
c:vcprojectstest.cpp(263) :fatal error C1010: unexpected end of file while looking for precompiled header
directive
Answer 2: This error occurs when the Microsoft Visual C++ compiler is set to use precompiled headers but one
(or more) of your C++ code files does not include the stdafx header as the first line. To fix this problem, simply

locate the file(s) producing the error (in the above error, test.cpp is the culprit), and add the following line at the
very top of the file(s):
1 #include "stdafx.h"

Note that for programs with multiple files, every C++ code file needs to start with this line.
Alternatively, you can turn off precompiled headers.
Problem 3: When trying to use cin, cout, or endl, the compiler says cin, cout, or endl is an undeclared
identifier
Answer 3: First, make sure you have included the following line near the top of your file:
1 #include <iostream>

Second, make sure cin, cout, and endl are prefixed by std::. For example:
1 std::cout << "Hello world!" << std::endl;

Problem 4: When trying to use endl to end a printed line, the compiler says end1 is an undeclared
identifier
Answer 4: Make sure you do not mistake the letter l (lower case L) in endl for the number 1. endl is all letters. I
recommend using a font that makes it clear the differences between the letter lower case L, upper case i, and the
number 1. Also the letter capital o and the number zero can easily be confused in many non-programming fonts.
Problem 5: My program compiles but it isnt working correctly. What do I do?
Answer 5: Debug it! You can find information on how to debug programs in lesson 1, specifically sections 1.11 -Debugging your program (stepping and breakpoints) and 1.11a -- Debugging your program (watching variables
and the call stack).
Problem 6: How do I turn on line numbering in Visual Studio?
Answer 6: Go to the Tools Menu, and choose Options. Under the Text Editor submenu, choose All Languages (or
C/C++), and youll see a checkbox on the right for Line numbers.
Problem 7: When I compile my program in Visual Studio 2010, I get an error message about a COFF file
being invalid. How do I fix this?
Answer 7: If you see the following error when compiling with Visual Studio 2010:
LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt

Youve encountered a Microsoft OS/compiler incompatibility. It has nothing to do with your code.
The best first option is to download and install Visual Studio 2010 Service Pack 1.
If that does not fix your issue, there are many other good suggestions on this Stack Overflow thread about the
various causes and solutions to this problem.
Problem 8: When I compile my program, I get an error about unresolved external symbol _main or
_WinMain@16
Answer 8: This means your compiler cant find your main() function. All programs must include a main()
function.
There are a few things to check:
a) Does your code include a function named main?
b) Is main spelled correctly?
c) Is the file containing main part of your project? (if not, either move the main function to one that is, or add the
file to your project. See lesson 1.8 -- Programs with multiple files for more information about how to do this).
d) Is the file containing function main set to compile? (Also see lesson 1.8 -- Programs with multiple files for more
information about how to do this).
Problem 9: When I compile my program, I get a warning about Cannot find or open the PDB file
Answer 9: This is a warning, not an error, so it shouldnt impact your program working. However, it is annoying.
To fix it, go into the Debug menu -> Options and Settings -> Symbols, and check Microsoft Symbol Server.
Problem 10: Im using Code::Blocks or g++ on the command line, and none of the C++11 functionality
works
Answer 10: For Code::Blocks, go to Project->Build options->Compiler settings->Compiler flags and check Have
g++ follow C++11 ISO C++ language standard
See lesson 0.5 -- Installing an Integrated Development Environment (IDE) for pictures of how to do this.
For compiling with g++ on the command line, add the following to the command line: -std=c++11
Problem 11: Im using Visual Studio and get the following error: 1>MSVCRTD.lib(exe_winmain.obj) :
error LNK2019: unresolved external symbol _WinMain@16 referenced in function int __cdecl
invoke_main(void) (?invoke_main@@YAHXZ)
Answer 11: Most likely youve created the wrong type of project. Make sure youre creating a Win32 Console
Application, not a Win32 Project.
Problem 12: I ran my program and get a window but no output.
Answer 12: Your virus scanner may be blocking execution. Try disabling it temporarily and see if thats the issue.

I have some other problem that I cant figure out. How can I get an answer quickly?
As you progress through the material, youll undoubtedly have questions or run into unexpected problems. What to
do next depends on your problem. But in general, there are a few things you can try.
First, ask Google. Find a good way to phrase your question and do a Google search. If you have received an error
message, paste the exact message into google using quotes.
Odds are someone has already asked the same question and there is an answer waiting for you.
If that fails, ask on a Q&A board. There are websites designed for programming questions and answers, like
Stack Overflow. Try posting your question there. Remember to be thorough about what your problem is, and
include all relevant information like what OS youre on and what IDE youre using.

STRUCTURE OF A PROGRAM
A computer program is a sequence of instructions that tell the computer what to do.
Statements
The most common type of instruction in a program is the statement. A statement in C++ is the smallest
independent unit in the language. In human language, it is analogous to a sentence. We write sentences in order to
convey an idea. In C++, we write statements in order to convey to the compiler that we want to perform a task.
Statements in C++ are terminated by a semicolon.
There are many different kinds of statements in C++. The following are some of the most common types of simple
statements:
1 int x;
2 x = 5;
3 std::cout << x;
int x

is a declaration statement. This particular declaration statement tells the compiler that x is a variable that
holds an integer (int) value. In programming, a variable provides a name for a region of memory that can hold a
value that can vary. All variables in a program must be declared before they are used. We will talk more about
variables shortly.
x = 5

is an assignment statement. It assigns a value (5) to a variable (x).

std::cout << x;

is an output statement. It outputs the value of x (which we set to 5 in the previous statement)

to the screen.
Expressions
The compiler is also capable of resolving expressions. An expression is a mathematical entity that evaluates to a
value. For example, in math, the expression 2+3 evaluates to the value 5. Expressions can involve values (such as
2), variables (such as x), operators (such as +) and functions (which return an output value based on some input
value). They can be singular (such as 2, or x), or compound (such as 2+3, 2+x, x+y, or (2+x)*(y-3)).
For example, the statement x = 2 + 3; is a valid assignment statement. The expression 2 + 3 evaluates to the
value of 5. This value of 5 is then assigned to x.
Functions
In C++, statements are typically grouped into units called functions. A function is a collection of statements that
executes sequentially. Every C++ program must contain a special function called main. When the C++ program is
run, execution starts with the first statement inside of function main. Functions are typically written to do a very
specific job. For example, a function named max might contain statements that figures out which of two

numbers is larger. A function named calculateGrade might calculate a students grade. We will talk more about
functions later.
Helpful hint: Its a good idea to have your main() function live in a .cpp file named either main.cpp, or with the
same name as your project. For example, if you are writing a Chess game, put your main() function in chess.cpp.
Libraries and the C++ Standard Library
A library is a collection of precompiled code (e.g. functions) that has been packaged up for reuse in many
different programs. Libraries provide a common way to extend what your programs can do. For example, if you
were writing a game, youd probably want to include a sound library and a graphics library.
The C++ core language is actually very small and minimalistic (and youll learn most of it in these tutorials).
However, C++ also comes with a library called the C++ standard library that provides additional functionality
for your use. The C++ standard library is divided into areas (sometimes also called libraries, even though theyre
just parts of the standard library), each of which focus on providing a specific type of functionality. One of the
most commonly used parts of the C++ standard library is the iostream library, which contains functionality for
writing to the screen and getting input from a console user.
Taking a look at a sample program
Now that you have a brief understanding of what statements, functions, and libraries are, lets look at a simple
hello world program:
1 #include <iostream>
2
3 int main()
4{
5 std::cout << "Hello world!";
6 return 0;
7}
Line 1 is a special type of statement called a preprocessor directive. Preprocessor directives tell the compiler to
perform a special task. In this case, we are telling the compiler that we would like to add the contents of the
iostream header to our program. The iostream header allows us to access functionality from the iostream library,
which will allow us to write to the screen.
Line 2 is blank, and is ignored by the compiler.
Line 3 declares the main() function, which as you learned above, is mandatory. Every program must have a main()
function.
Lines 4 and 7 tell the compiler which lines are part of the main function. Everything between the opening curly
brace on line 4 and the closing curly brace on line 7 is considered part of the main() function.

Line 5 is our first statement (you can tell its a statement because it ends with a semicolon), and it is an output
statement. std::cout is a special object that represents the console/screen. The << symbol is an operator (much like
+ is an operator) called the output operator. std::cout understands that anything sent to it via the output operator
should be printed on the screen. In this case, were sending it the text Hello world!.
Line 6 is a new type of statement, called a return statement. When an executable program finishes running, the
main() function sends a value back to the operating system that indicates whether it was run successfully or not.
This particular return statement returns the value of 0 to the operating system, which means everything went
okay!. Non-zero numbers are typically used to indicate that something went wrong, and the program had to abort.
We will discuss return statements in more detail when we discuss functions.
All of the programs we write will follow this template, or a variation on it. We will discuss each of the lines above
in more detail in the upcoming sections.
Syntax and syntax errors
In English, sentences are constructed according to specific grammatical rules that you probably learned in English
class in school. For example, normal sentences end in a period. The rules that govern how sentences are
constructed in a language is called syntax. If you forget the period and run two sentences together, this is a
violation of the English language syntax.
C++ has a syntax too: rules about how your programs must be constructed in order to be considered valid. When
you compile your program, the compiler is responsible for making sure your program follows the basic syntax of
the C++ language. If you violate a rule, the compiler will complain when you try to compile your program, and
issue you a syntax error.
For example, you learned above that statements must end in a semicolon.
Lets see what happens if we omit the semicolon in the following program:
1 #include <iostream>
2
3 int main()
4{
5 std::cout << "Hello world!"
6 return 0;
7}
Visual studio produces the following error:
c:\users\apomeranz\documents\visual studio 2013\projects\test1\test1\test1.cpp(6): error
C2143: syntax error : missing ';' before 'return'

This is telling you that you have an syntax error on line 6: Youve forgotten a semicolon before the return. In this
case, the error is actually at the end of line 5. Often, the compiler will pinpoint the exact line where the syntax
error occurs for you. However, sometimes it doesnt notice until the next line.
Syntax errors are common when writing a program. Fortunately, theyre often easily fixable. The program can
only be fully compiled (and executed) once all syntax errors are resolved.
Quiz
The following quiz is meant to reinforce your understanding of the material presented above.
1) What is the difference between a statement and an expression?
2) What is the difference between a function and a library?
3) What symbol do statements in C++ end with?
4) What is a syntax error?
Quiz Answers
1) A statement is a complete sentence that tells the compiler to perform a particular task. An expression is a
mathematical entity that evaluates to a value. Expressions are often used inside of statements.
2) A function is a collection of statements that executes sequentially, typically designed to perform a specific job. A
library is a collection of functions packaged for use in multiple programs.
3) The semicolon (;)
4) A syntax error is a compiler error that occurs at compile-time when your program violates the grammar rules of the
C++ language.

COMMENTS
Types of comments
A comment is a line (or multiple lines) of text that are inserted into the source code to explain what the code is
doing. In C++ there are two kinds of comments.
The // symbol begins a C++ single-line comment, which tells the compiler to ignore everything to the end of the
line. For example:
1 std::cout << "Hello world!" << std::endl; // Everything from here to the right is ignored.
Typically, the single line comment is used to make a quick comment about a single line of code.
1 std::cout << "Hello world!" << std::endl; // cout and endl live in the iostream library
2 std::cout << "It is very nice to meet you!" << std::endl; // these comments make the code hard to read
3 std::cout << "Yeah!" << std::endl; // especially when lines are different lengths
Having comments to the right of a line can make both the code and the comment hard to read, particularly if the
line is long. Consequently, the // comment is often placed above the line it is commenting.
1 // cout and endl live in the iostream library
2 std::cout << "Hello world!" << std::endl;
3
4 // this is much easier to read
5 std::cout << "It is very nice to meet you!" << std::endl;
6
7 // don't you think so?
8 std::cout << "Yeah!" << std::endl;
The /* and */ pair of symbols denotes a C-style multi-line comment. Everything in between the symbols is
ignored.
1 /* This is a multi-line comment.
2 This line will be ignored.
3 So will this one. */
Since everything between the symbols is ignored, you will sometimes see programmers beautify their multiline
comments:
1 /* This is a multi-line comment.
2 * the matching asterisks to the left
3 * can make this easier to read
4 */

Multi-line style comments do not nest. Consequently, the following will have unexpected results:
1 /* This is a multi-line /* comment */ this is not inside the comment */
2 // The above comment ends at the first */, not the second */
Rule: Never nest comments inside of other comments.
Proper use of comments
Typically, comments should be used for three things. For a given library, program, or function, comments are best
used to describe what the library, program, or function, does. For example:
1 // This program calculate the student's final grade based on his test and homework scores.
1 // This function uses newton's method to approximate the root of a given equation.
1 // The following lines generate a random item based on rarity, level, and a weight factor.
All of these comments give the reader a good idea of what the program is trying to accomplish without having to
look at the actual code. The user (possibly someone else, or you if youre trying to reuse code youve already
previously written) can tell at a glance whether the code is relevant to what he or she is trying to accomplish. This
is particularly important when working as part of a team, where not everybody will be familiar with all of the code.
Second, within a library, program, or function described above, comments can be used to describe how the code is
going to accomplish its goal.
1 /* To calculate the final grade, we sum all the weighted midterm and homework scores
2 and then divide by the number of scores to assign a percentage. This percentage is
3 used to calculate a letter grade. */
1 // To generate a random item, we're going to do the following:
2 // 1) Put all of the items of the desired rarity on a list
3 // 2) Calculate a probability for each item based on level and weight factor
4 // 3) Choose a random number
5 // 4) Figure out which item that random number corresponds to
6 // 5) Return the appropriate item
These comments give the user an idea of how the code is going to accomplish its goal without going into too
much detail.
At the statement level, comments should be used to describe why the code is doing something. A bad statement
comment explains what the code is doing. If you ever write code that is so complex that needs a comment to
explain what a statement is doing, you probably need to rewrite your statement, not comment it.
Here are some examples of bad line comments and good statement comments.
Bad comment:

1 // Set sight range to 0


2 sight = 0;
(yes, we already can see that sight is being set to 0 by looking at the statement)
Good comment:
1 // The player just drank a potion of blindness and can not see anything
2 sight = 0;
(now we know WHY the players sight is being set to 0)
Bad comment:
1 // Calculate the cost of the items
2 cost = items / 2 * storePrice;
(yes, we can see that this is a cost calculation, but why is items divided by 2?)
Good comment:
1 // We need to divide items by 2 here because they are bought in pairs
2 cost = items / 2 * storePrice;
(now we know!)
Programmers often have to make a tough decision between solving a problem one way, or solving it another way.
Comments are a great way to remind yourself (or tell somebody else) the reason you made one decision instead of
another.
Good comments:
1 // We decided to use a linked list instead of an array because
2 // arrays do insertion too slowly.
1 // We're going to use newton's method to find the root of a number because
2 // there is no deterministic way to solve these equations.
Finally, comments should be written in a way that makes sense to someone who has no idea what the code does. It
is often the case that a programmer will say Its obvious what this does! Theres no way Ill forget about this.
Guess what? Its not obvious, and you will be amazed how quickly you forget. You (or someone else) will thank
you later for writing down the what, how, and why of your code in human language. Reading individual lines of
code is easy. Understanding what goal they are meant to accomplish is not.
To summarize:

At the library, program, or function level, describe what


Inside the library, program, or function, describe how
At the statement level, describe why.

Commenting out code


Converting one or more lines of code into a comment is called commenting out your code. This provides a
convenient way to (temporarily) exclude parts of your code from being included in your compiled program.
To comment out a single line of code, simply use the // style comment to turn a line of code into a comment
temporarily:
Uncommented out:
1

std::cout << 1;

Commented out:
1 //

std::cout << 1;

To comment out a block of code, use // on multiple lines of code, or the /* */ style comment to turn the block of
code into a comment temporarily.
Uncommented out:
1
2
3

std::cout << 1;
std::cout << 2;
std::cout << 3;

Commented out:
1 //
2 //
3 //

std::cout << 1;
std::cout << 2;
std::cout << 3;

or
1 /*
2 std::cout << 1;
3 std::cout << 2;
4 std::cout << 3;
5 */
There are quite a few reasons you might want to do this:

1) Youre working on a new piece of code that wont compile yet, and you need to run the program. The compiler
wont let you run if there are compiler errors. Commenting out the code that wont compile will allow the program
to compile so you can run it. When youre ready, you can uncomment the code, and continue working on it.
2) Youve written code that compiles but doesnt work correctly, and you dont have time to fix it until later.
Commenting out the broken code will ensure the broken code doesnt execute and cause problems until you can
fix it.
3) To find the source of an error. If a program isnt producing the desired results (or is crashing), it can be useful in
some cases to disable parts of your code to see if you can isolate whats causing it to not work correctly. If you
comment out one or more lines of code, and your program starts working as expected (or stops crashing), odds are
whatever you last commented out was part of the problem. You can then investigate why those lines of code are
causing the problem.
4) You want to replace one piece of code with another piece of code. Instead of just deleting the original code, you
can comment it out and leave it there for reference until youre sure your new code works properly. Once you are
sure your new code is working, you can remove the old commented out code. If you cant get your new code to
work, you can always delete the new code and uncomment the old code to revert back to what you had before.
Commenting out code is a common thing to do while developing, so many IDEs provide support for commenting
out a highlighted section of code. How you access this functionality varies by IDE (in Visual Studio, you can find
it in the Edit menu under Edit->Advanced->Comment Selection/Uncomment Selection).

A FIRST LOOK AT VARIABLES, INITIALIZATION, AND


ASSIGNMENT
Variables
A statement such as x = 5; seems obvious enough. As you would guess, we are assigning the value of 5 to x. But
what exactly is x? x is a variable.
A variable in C++ is a name for a piece of memory that can be used to store information. You can think of a
variable as a mailbox, or a cubbyhole, where we can put and retrieve information. All computers have memory,
called RAM (random access memory), that is available for programs to use. When a variable is defined, a piece of
that memory is set aside for the variable.
In this section, we are only going to consider integer variables. An integer is a number that can be written without
a fractional component, such as -12, -1, 0, 4, or 27. An integer variable is a variable that holds an integer value.
In order to define a variable, we generally use a special kind of declaration statement called a definition (well
explain the precise difference between a declaration and a definition later). Heres an example of defining variable
x as an integer variable (one that can hold integer values):
1 int x;

When this statement is executed by the CPU, a piece of memory from RAM will be set aside (called
instantiation). For the sake of example, lets say that the variable x is assigned memory location 140. Whenever
the program sees the variable x in an expression or statement, it knows that it should look in memory location 140
to get the value.
One of the most common operations done with variables is assignment. To do this, we use the assignment
operator, more commonly known as the = symbol. For example:
1 x = 5;

When the CPU executes this statement, it translates this to put the value of 5 in memory location 140.
Later in our program, we could print that value to the screen using std::cout:
1 std::cout << x; // prints the value of x (memory location 140) to the console

l-values and r-values

In C++, variables are a type of l-value (pronounced ell-value). An l-value is a value that has an address (in
memory). Since all variables have addresses, all variables are l-values. The name l-value came about because lvalues are the only values that can be on the left side of an assignment statement. When we do an assignment, the
left hand side of the assignment operator must be an l-value. Consequently, a statement like 5 = 6; will cause a
compile error, because 5 is not an l-value. The value of 5 has no memory, and thus nothing can be assigned to it. 5
means 5, and its value can not be reassigned. When an l-value has a value assigned to it, the current value at that
memory address is overwritten.
The opposite of l-values are r-values (pronounced arr-values). An r-value refers to any value that can be assigned
to an l-value. r-values are always evaluated to produce a single value. Examples of r-values are single numbers
(such as 5, which evaluates to 5), variables (such as x, which evaluates to whatever value was last assigned to it),
or expressions (such as 2 + x, which evaluates to the value of x plus 2).
Here is an example of some assignment statements, showing how the r-values evaluate:
1 int y;

// define y as an integer variable

2 y = 4;

// 4 evaluates to 4, which is then assigned to y

3 y = 2 + 5; // 2 + 5 evaluates to 7, which is then assigned to y


4
5 int x;

// define x as an integer variable

6 x = y;

// y evaluates to 7 (from before), which is then assigned to x.

7 x = x;

// x evaluates to 7, which is then assigned to x (useless!)

8 x = x + 1; // x + 1 evaluates to 8, which is then assigned to x.

Lets take a closer look at the last assignment statement above, since it causes the most confusion.
1 x = x + 1;

In this statement, the variable x is being used in two different contexts. On the left side of the assignment operator,
x is being used as an l-value (variable with an address). On the right side of the assignment operator, x is being
used as an r-value, and will be evaluated to produce a value (in this case, 7). When C++ evaluates the above
statement, it evaluates as:
1 x = 7 + 1;

Which makes it obvious that C++ will assign the value 8 back into variable x.

Programmers dont tend to talk about l-values or r-values much, so its not that important to remember the terms.
The key takeaway is that on the left side of the assignment, you must have something that represents a memory
address (such as a variable). Everything on the right side of the assignment will be evaluated to produce a value.
Initialization vs. assignment
C++ supports two related concepts that new programmers often get mixed up: assignment and initialization.
After a variable is defined, a value may be assigned to it via the assignment operator (the = sign):
1 int x; // this is a variable definition
2 x = 5; // assign the value 5 to variable x

C++ will let you both define a variable AND give it an initial value in the same step. This is called initialization.
1 int x = 5; // initialize variable x with the value 5

A variable can only be initialized when it is defined.


Although these two concepts are similar in nature, and can often be used to achieve similar ends, well see cases in
future lessons where some types of variables require an initialization value, or disallow assignment. For these
reasons, its useful to make the distinction now.
Uninitialized variables
Unlike some programming languages, C/C++ does not initialize variables to a given value (such as zero)
automatically (for performance reasons). Thus when a variable is assigned to a memory location by the compiler,
the default value of that variable is whatever garbage happens to already be in that memory location! A variable
that has not been assigned a value is called an uninitialized variable.
Note: Some compilers, such as Visual Studio, will initialize the contents of memory when youre using a debug
build configuration. This will not happen when using a release build configuration.
Uninitialized variables can lead to interesting (and by interesting, we mean unexpected) results. Consider the
following short program:
1 // #include "stdafx.h" // Uncomment if Visual Studio user
2 #include <iostream>
3

4 int main()
5 {
6

// define an integer variable named x

int x;

8
9

// print the value of x to the screen (dangerous, because x is uninitialized)

10

std::cout << x;

11
12

return 0;

13 }

In this case, the computer will assign some unused memory to x. It will then send the value residing in that
memory location to cout, which will print the value. But what value will it print? The answer is who knows!,
and the answer may change every time you run the program. When the author ran this program with the Visual
Studio 2013 compiler, std::cout printed the value 7177728 one time, and 5277592 the next.
A couple of notes if you want to run this program yourself:

Make sure youre using a release build configuration (see section 0.6a -- Build configurations for information on
how to do that). Otherwise the above program may print whatever value your compiler is initializing memory with
(Visual Studio uses -858993460).
If your compiler wont let you run this program because it flags variable x as an uninitialized variable, a possible
solution to get around this issue is noted in the comments section.

Using uninitialized variables is one of the most common mistakes that novice programmers make, and
unfortunately, it can also be one of the most challenging to debug (because the program may run fine anyway if the
uninitialized value happened to get assigned to a spot of memory that had a reasonable value in it, like 0).
Fortunately, most modern compilers will print warnings at compile-time if they can detect a variable that is used
without being initialized. For example, compiling the above program on Visual Studio 2005 express produced the
following warning:
c:vc2005projectstesttesttest.cpp(11) : warning C4700: uninitialized local variable 'x' used

A good rule of thumb is to initialize your variables. This ensures that your variable will always have a consistent
value, making it easier to debug if something goes wrong somewhere else.
Rule: Initialize your variables.

Quiz
What values does this program print?
1 int x = 5;
2 x = x - 2;
3 std::cout << x; // #1
4
5 int y = x;
6 std::cout << y; // #2
7
8 // x + y is an r-value in this context, so evaluate their values
9 std::cout << x + y; // #3
10
11 std::cout << x; // #4
12
13 int z;
14 std::cout << z; // #5

Quiz Answers
1)
2)
3)
4)
5)

The program outputs 3. x - 2 evaluates to 3, which was assigned to x.


The program outputs 3. y was assigned the value of x, which evaluated to 3.
The program outputs 6. x + y evaluates to 6. There was no assignment here.
The program outputs 3. The value of x is still 3 because it was never reassigned.
The output is indeterminate. z is an uninitialized variable.

A FIRST LOOK AT COUT, CIN, AND ENDL


std::cout
As noted in previous sections, the std::cout object (in the iostream library) can be used to output text to the
console. As a reminder, heres our Hello world program:
1 #include <iostream>
2
3 int main()
4{
5

std::cout << "Hello world!";

return 0;

7}

To print more than one thing on the same line, the output operator (<<) can be used multiple times. For example:
1 #include <iostream>
2
3 int main()
4{
5

int x = 4;

std::cout << "x is equal to: " << x;

return 0;

8}

This program prints:


x is equal to: 4

What would you expect this program to print?


1 #include <iostream>
2
3 int main()
4{
5

std::cout << "Hi!";

std::cout << "My name is Pranav.";

return 0;

8}

You might be surprised at the result:


Hi!My name is Pranav.

std::endl
If we want to print things to more than one line, we can do that by using std::endl. When used with std::cout,
std::endl inserts a newline character (causing the cursor to go to the start of the next line).
For example:
1 #include <iostream>
2
3 int main()
4{
5

std::cout << "Hi!" << std::endl;

std::cout << "My name is Pranav." << std::endl;

return 0;

8}

This prints:

Hi!
My name is Pranav.

std::cin
std::cin is the opposite of std::cout -- whereas std::cout prints data to the console using the output operator (<<),
std::cin reads input from the user at the console using the input operator (>>). Now that you have a basic
understanding of variables, we can use std::cin to get input from the user and store it in a variable.
1 //#include "stdafx.h" // Uncomment this line if using Visual Studio
2 #include <iostream>
3
4 int main()
5 {
6

std::cout << "Enter a number: "; // ask user for a number

int x; // no need to initialize x since we're going to overwrite that value on the very next line

std::cin >> x; // read number from console and store it in x

std::cout << "You entered " << x << std::endl;

10

return 0;

11 }

Try compiling this program and running it for yourself. When you run the program, it will print Enter a number:
and then wait for you to enter one. Once you enter a number (and press enter), it will print You entered
followed by the number you just entered.
For example (I entered 4):
Enter a number: 4
You entered 4

This is an easy way to get input from the user, and we will use it in many of our examples going forward.
If your screen closes immediately after entering a number, please see section a few common cpp problems for a
solution.

(As an interesting side note, if you enter a really big number, the results may surprise you. Try it! This happens
because x can only hold numbers up to a certain size. After that, it overflows. Well discuss overflow in a future
section.)
std::cin, std::cout, <<, and >>
New programmers often mix up std::cin, std::cout, << and >>. Heres an easy way to remember:

std::cin and cout always go on the left-hand side of the statement.


std::cout is used to output a value (cout = output)
std::cin is used to get an input value (cin = input)
<< is used with std::cout, and shows the direction that data is moving from the r-value to the console. std::cout
<< 4 moves the value of 4 to the console

>> is used with std::cin, and shows the direction that data is moving from the console into the variable. std::cin
>> x moves the value from the console into x

A FIRST LOOK AT FUNCTIONS AND RETURN VALUES


A function is a reusable sequence of statements designed to do a particular job. You already know that every
program must have a function named main() (which is the where the program starts execution). However, most
programs use many functions.
Often, your program needs to interrupt what it is doing to temporarily do something else. You do this in real life
all the time. For example, you might be reading a book when you remember you need to make a phone call. You
put a bookmark in your book, make the phone call, and when you are done with the phone call, you return to your
book where you left off.
C++ programs work the same way. A program will be executing statements sequentially inside one function when
it encounters a function call. A function call is an expression that tells the CPU to interrupt the current function
and execute another function. The CPU puts a bookmark at the current point of execution, and then calls
(executes) the function named in the function call. When the called function terminates, the CPU goes back to the
point it bookmarked, and resumes execution.
The function initiating the function call is called the caller, and the function being called is the callee or called
function.
Here is a sample program that shows how new functions are defined and called:
1 //#include <stdafx.h> // Visual Studio users need to uncomment this line
2 #include <iostream> // for std::cout and std::endl
3
4 // Definition of function doPrint()
5 void doPrint() // doPrint() is the called function in this example
6 {
7

std::cout << "In doPrint()" << std::endl;

8 }
9
10 // Definition of function main()
11 int main()
12 {

13

std::cout << "Starting main()" << std::endl;

14

doPrint(); // Interrupt main() by making a function call to doPrint(). main() is the caller.

15

std::cout << "Ending main()" << std::endl;

16

return 0;

17 }

This program produces the following output:


Starting main()
In doPrint()
Ending main()

This program begins execution at the top of function main(), and the first line to be executed prints Starting
main(). The second line in main() is a function call to the function doPrint(). At this point, execution of statements
in main() is suspended, and the CPU jumps to doPrint(). The first (and only) line in doPrint prints In doPrint().
When doPrint() terminates, the caller (main()) resumes execution where it left off. Consequently, the next
statement executed in main prints Ending main().
Note that function calls are made by using the function name, plus a parameter list enclosed in parenthesis (). In
this case, since none of our functions use parameters, the list is empty. Well talk more about function parameters
in the next lesson. If you forget the parameters list, the function will not be called!
Return values
If you remember, when the main() function finishes executing, it returns an integer value back to the operating
system (the caller) by using a return statement.
Functions you write can return a single value to their caller as well. We do this by setting the return type of the
function in the functions definition. The return type is the type declared before the function name.
A return type of void means the function does not return a value. A return type of int means the function returns an
integer value to the caller.
1 // void means the function does not return a value to the caller
2 void returnNothing()
3 {
4

std::cout << "Hi" << std::endl;

// This function does not return a value so no return statement is needed

6 }
7
8 // int means the function returns an integer value to the caller
9 int return5()
10 {
11

return 5; // this function returns an integer, so a return statement is needed

12 }

Lets use these functions in a program:


1 #include <iostream>
2
3 // void means the function does not return a value to the caller
4 void returnNothing()
5 {
6

std::cout << "Hi" << std::endl;

// This function does not return a value so no return statement is needed

8 }
9
10 // int means the function returns an integer value to the caller
11 int return5()
12 {
13

return 5; // this function returns an integer, so a return statement is needed

14 }
15
16 int main()

17 {
18

std::cout << return5() << std::endl; // prints 5

19

std::cout << return5() + 2 << std::endl; // prints 7

20
21

returnNothing(); // okay: function returnNothing() is called, no value is returned

22

return5(); // okay: function return5() is called, return value is discarded

23
24

std::cout << returnNothing(); // This line will not compile. You'll need to comment it out to continue.

25
26

return 0;

27 }

In the first function call, return5() is executed. The function returns the value of 5 back to the caller, which passes
that value to cout to be output.
In the second function call, return5() is executed and returns the value of 5 back to the caller. The expression 5 + 2
is then evaluated to 7. The value of 7 is passed to cout to be output.
In the third function call, returnNothing() is executed. The function itself prints Hi and then returns nothing back
to the caller. Control returns to main() and the program proceeds.
In the fourth function call, return5() is executed. The value 5 is returned to main(), but main() does nothing with
the return value so the return value is discarded.
In the fifth function call, returnNothing() returns void back to main(). main() then tries to send this value to
std::cout. However, this is invalid, as you cant send a void value to be output (what would it actually output?).
Consequently, the compiler will give you an error when you try to compile this line. The only valid thing you can
do with void return values is ignore them. Youll need to comment out this line of code in order to make your code
compile.
One commonly asked question is, Can my function return multiple values using a return statement?. The answer
is no. Functions can only return a single value using a return statement. However, there are ways to work around
the issue, which we will discuss when we get into the in-depth section on functions.

Returning to main
You now have the conceptual tools to understand how the main() function actually works. When the program is
executed, the operating system makes a function call to main(). Execution then jumps to the top of main. The
statements in main are executed sequentially. Finally, main returns a integer value (usually 0) back to the operating
system. This is why main is defined as int main().
Why return a value back to the operating system? This value is called a status code, and it tells the operating
system (and any other programs that called yours) whether your program executed successfully or not. By
consensus, a return value of 0 means success, and a positive return value means failure.
Note that the C++ standard explicitly specifies that main() must return an int. However, if you do not provide a
return statement in main, the compiler will return 0 on your behalf. However, it is generally a good idea to
explicitly return a value from main, both to show your intent, and for consistency with other functions (which will
not let you omit the return value).
For now, you should also define your main() function at the bottom of your code file. Well talk about why
shortly, in section 1.7 -- Forward Declarations.
Reusing functions
The same function can be called multiple times, which is useful if you need to do something more than once.
1 //#include <stdafx.h> // Visual Studio users need to uncomment this line
2 #include <iostream>
3
4 // getValueFromUser will read a value in from the user, and return it to the caller
5 int getValueFromUser()
6 {
7

std::cout << "Enter an integer: ";

int a;

std::cin >> a;

10

return a;

11 }
12

13 int main()
14 {
15

int x = getValueFromUser(); // first call to getValueFromUser

16

int y = getValueFromUser(); // second call to getValueFromUser

17
18

std::cout << x << " + " << y << " = " << x + y << std::endl;

19
20

return 0;

21 }

This program produces the following output:


Enter an integer: 5
Enter an integer: 7
5 + 7 = 12

In this case, main() is interrupted 2 times, once for each call to getValueFromUser(). Note that in both cases, the
value read into variable a is passed back to main() via the functions return value and then assigned to variable x or
y!
Note that main() isnt the only function that can call other functions. Any function can call another function!
1 //#include <stdafx.h> // Visual Studio users need to uncomment this line
2 #include <iostream>
3
4 void printA()
5 {
6

std::cout << "A" << std::endl;

7 }
8
9 void printB()

10 {
11

std::cout << "B" << std::endl;

12 }
13
14 // function printAB() calls both printA() and printB()
15 void printAB()
16 {
17

printA();

18

printB();

19 }
20
21 // Definition of main()
22 int main()
23 {
24

std::cout << "Starting main()" << std::endl;

25

printAB();

26

std::cout << "Ending main()" << std::endl;

27

return 0;

28 }

This program produces the following output:


Starting main()
A
B
Ending main()

Nested functions
Functions can not be defined inside other functions (called nesting) in C++. The following program is not legal:
#include <iostream>

int main()
{
1

int foo() // this function is nested inside main(), which is illegal.

std::cout << "foo!" << std::endl;

return 0;

6
7

foo();

return 0;

9 }
10
11
12
13

The proper way to write the above program is:


1 #include <iostream>
2
3 int foo() // no longer inside of main()
4 {
5

std::cout << "foo!" << std::endl;

return 0;

7 }
8
9 int main()
10 {
11

foo();

12

return 0;

13 }

You might also like