The Parts of a C++ Program: Functions, Variables, Statements and More
Table of Contents
In the first lesson I showed you how to compile and run a simple C++ program but I didn't tell you what the different parts of the program mean. In this lesson, we'll take a quick look at what a computer program is, what the standard program development cycle looks like and what the different parts of a simple C++ program are. We'll also show you three different ways to access library commands in the standard namespace.
What is a Program?
First of all, what is a program? Well, the simple answer is that a computer program is a series of instructions written by a programmer that tells a computer what to do. Of course, in reality it's much more complicated than that, and a lot more interesting.
The Program Development Cycle
Programs never consist of only a single file. When a programmer writes a program, they have to write it in a special language known as a programming language (like C++, C#, or Java). Programmers write their programs in plain text editors, usually, the text editor that is included with their integrated development environment (IDE). (MSVC++ is an IDE.) A plain text file containing instructions in a programming language is known as a source file. (It's often referred to as the source code.)
No computer is smart enough to understand the contents of a source file. Before a computer can understand the instructions, the source file has to be translated into machine code, which is literally a long series of 1s and 0s. Programmers use one of two devices to translate source code into machine code: a compiler, which translates source code before the application is ready to use, and an interpreter, which translates source code while the application is being used. C++ is a compiled language, which means that you need a compiler to create C++ files. (MSVC++ includes a compiler as part of its IDE. In fact, the compiler is such an important part of the IDE that MSVC++ is often referred to as a compiler, even though it includes many other tools.)
Many compilers come with a tool known as a preprocessor. Preprocessors are used to get a source file ready for compilation. Programmers can use preprocessor directives to perform simple operations like text substitution, including the contents of other files in the source file, and conditional compilation, where outside conditions are used to determine which parts of the source file are compiled or if it is even compiled at all. Once all of these house-keeping operations have been performed on the source file, it is sent to the compiler.
The file that is created when a compiler translates a source file into machine language is known as an object file. Object files are not usually self-sufficient programs. Almost every program has to refer to instructions in one or more other object files to work properly. These external files come in one of two types: static libraries and dynamic-link librarires. Links to static libraries are resolved during the linking stage before an application is released to the public. Links to dynamic link libraries (DLLs) are resolved while the program is running.
To resolve these links (or symbols) between object files, another program has to be used known as a linker. Linkers connect object files to libraries to create an executable which is the finished program file used by the end-user when he or she wants to run your program. Linkers are usually included along with the plain text editor and the compiler as part of an IDE. (Many executables also require external data resources, but we'll talk about that kind of stuff later.)
Of course, no program more than a few lines long works correctly the first time, which is why IDEs include built-in debuggers. A debugger is a tool that allows you to follow the operation of your program as it is being executed, allowing you to keep an eye on variables and interrupt program flow at predesignated times. The sad truth is that a lot of your time is going to be spent debugging your code so don't be afraid to make the debugger your friend.
As you can see, to create a program, you need to perform a lot of steps and enlist the aid of a lot of additional tools. While this process may seem overwhelmingly complex at first, you'll find with time and experience that it all starts to make sense.
The Meaning of Life Program
Open MSVC++ and create a new project using the process outlined in the first tutorial. Type the following source code into your source file:
// Meaning Of Life
// A simple program that prints the value of a variable to the screen.
#include <iostream>
int theMeaningOfLife;
int main()
{
std::cout << "The Meaning of Life is...";
theMeaningOfLife = 42;
std::cout << theMeaningOfLife << std::endl;
return 0;
}
Save your file, then debug your program to compile it following the instructions in the first lesson. Assuming everything goes correctly, create a batch file and run your program. Your output should look like this:

Let's take this program apart and see how it works.
Comments
The first two lines of our program, the ones that begin with two forward slashes (//), are comments. I'll talk a lot more about comments later, but for now you might like to know that comments are completely ignored by the compiler; in fact, they're stripped from the program during compilation, so you can add as many comments as you like and they won't affect your program's size or performance. You could write War and Peace in your comments and it wouldn't affect your program. The only 'negative' consequence of using comments is a slight increase in file size for your source code, which is only used for production, not distribution. That's trivial; use as many comments as you need to do the job properly.
Having said that, comments should only be used to communicate important information about your program to another programmer or to yourself at a later point in time, long after you've forgotten what the heck you were doing. Comments shouldn't be used as a 'band-aid' to fix sloppy code. Write clean, self-documenting code and only use comments to explain some particularly tricky piece of syntax. We'll come back to this topic a little later on.
The comments in the following program provide the name of the program and indicate it's intended use.
// Meaning Of Life
// A simple program that prints the value of a variable to the screen.
#include <iostream>
int theMeaningOfLife;
int main()
{
std::cout << "The Meaning of Life is...";
theMeaningOfLife = 42;
std::cout << theMeaningOfLife << std::endl;
return 0;
}
Preprocessor Directives
The first line of actual code in our program is a preprocessor directive. Preprocessor directives can be identified by the # (pound, number sign, or hash symbol) at the start of the line. The #include directive tells the preprocessor to include the entire contents of the file enclosed in angle brackets in the source code document at the location of the directive before compiling it. We'll talk more about including files and other uses for the preprocessor in later tutorials.
In this example, the #include statement is telling the preprocessor to include the contents of the iostream file in the program right after the comments, but before the next line of code.
// Meaning Of Life
// A simple program that prints the value of a variable to the screen.
#include <iostream>
int theMeaningOfLife;
int main()
{
std::cout << "The Meaning of Life is...";
theMeaningOfLife = 42;
std::cout << theMeaningOfLife << std::endl;
return 0;
}
Variables
The next line of code is a variable declaration. Variables are named storage locations held in RAM while the program is operating. Variables can hold a number of things, including numbers, words, and memory addresses. In this program, the variable theMeaningOfLife is declared to hold an integer ('int') value. C++ comes with a number of built-in variable, or data types, but you can also create custom variable types to handle all sorts of situations. We'll talk about this a lot more later on when we get to classes.
// Meaning Of Life
// A simple program that prints the value of a variable to the screen.
#include <iostream>
int theMeaningOfLife;
int main()
{
std::cout << "The Meaning of Life is...";
theMeaningOfLife = 42;
std::cout << theMeaningOfLife << std::endl;
return 0;
}
Functions
The next line of the program defines the main() function. A function is a self-contained section of code that performs a specific task. In the case of the main() function, that task is running the program. When you double-click on an application icon to run it, the operating system calls that application's main() function and the application takes over.
All functions consist of a return type (main() returns an 'int' type), a function name ('main'), a parameter list (between the parentheses '( )' following the name; in this case, main() doesn't have any parameters defined), and an opening and closing brace ('{ }') to contain the code that the function executes. We'll talk more about functions and their elements later.
// Meaning Of Life // A simple program that prints the value of a variable to the screen. #include <iostream> int theMeaningOfLife; int main() { std::cout << "The Meaning of Life is..."; theMeaningOfLife = 42; std::cout << theMeaningOfLife << std::endl; return 0; }
Statements
Functions use program statements to carry out tasks. In this case, that task is printing a message on the console. Here's a quick breakdown of what's going on in these statements:
- Although the first statement doesn't do much (it just prints the message "The Meaning of Life is...", to the console), there is a lot going on in this statement. The words inside the quotation marks are known as a string literal, a series of printable characters (letters, numbers, punctuation, whitespace, and other symbols). To print a string on the console, our program has to borrow an object from the standard C++ library. In this case, that happens to be the
iostreamlibrary file, which we included in the preprocessor directive near the start of the program. The complier knows to look for thecoutobject in the standard library because we told it where to look when we wrotestd::cout. The first half of that code snippet (std) refers to the namespace that an object occupies, in this case, the standard library. (A namespace is essentially an area code.) The double colons (::) are known as the scope resolution operator, which basically tells the compiler to look in the namespace on the left of the operator for the object on the right of the operator (in this case,cout). An object is a collection of functions and variables that can be used like a self-contained unit. In this case, the object is a representation of the console. You can think about it this way: when we need to print a string to the console, we walk over to the standard library and grab theiostreambox. Inside that box is thecoutobject which we plug into our code. This object tells our program how to print text on the screen. Then we put the string into thecoutobject by using the insertion operator (two left-pointing angle brackets<<). Since we're done with thecoutobject in this statement, we send our string to the console by ending the statement with a semi-colon;. The semi-colon tells the compiler that the statement is finished, like a period at the end of a sentence. Every C++ statement ends with a semi-colon and forgetting to type one, or typing a colon or other character by accident, is a very common cause of syntax errors.// Meaning Of Life // A simple program that prints the value of a variable to the screen. #include <iostream> int theMeaningOfLife; int main() { std::cout << "The Meaning of Life is..."; theMeaningOfLife = 42; std::cout << theMeaningOfLife << std::endl; return 0; } - The second statement is much more straightforward and assigns the value '
42' to the variabletheMeaningOfLife. When you assign a value (number, character, memory address, etc.) to a variable you use the assignment operator, the equal sign=. The left-hand side of the equal sign must be a variable; the right-hand side may be a literal value (like the number42) or a variable. If you try to assign a variable to a literal value (42 = theMeaningOfLife;) you will get a compiler error.// Meaning Of Life // A simple program that prints the value of a variable to the screen. #include <iostream> int theMeaningOfLife; int main() { std::cout << "The Meaning of Life is..."; theMeaningOfLife = 42; std::cout << theMeaningOfLife << std::endl; return 0; } - The third statement prints the value of the variable
theMeaningOfLifeto the console followed by a line break. Most of this statement we saw in the first statement. The line break is achieved by using a second object from the standard library, theendl, end-line or end-'L'. The object is retrieved in the same way as thecoutobject, by prefixing the name of the object with the name of the namespace and the scope resolution operator,std::. You might have noticed that the value of the variabletheMeaningOfLifeis printed on the screen without the need for quotation marks. The compiler knows to print the value of the variable instead of the name of the variable. If you had placed quotation marks around the variable name, it would have printed the variable name instead of42. You'll also notice that this statement uses the insertion operator (<<) twice to print two things on the screen in the same statement. You can print as many things to the console as you want in the same statement by plugging them together like Lego™ blocks using this operator.// Meaning Of Life // A simple program that prints the value of a variable to the screen. #include <iostream> int theMeaningOfLife; int main() { std::cout << "The Meaning of Life is..."; theMeaningOfLife = 42; std::cout << theMeaningOfLife << std::endl; return 0; } - In the last statement, the program returns the value
0to the operating system, essentially returning control to Windows. A return statement tells the program to leave the current function and return to its previous location in the last function it was in. If this had been a different function, it might have returned control to themain()function, but since it is the main function that is returning, control goes back to the operating system.// Meaning Of Life // A simple program that prints the value of a variable to the screen. #include <iostream> int theMeaningOfLife; int main() { std::cout << "The Meaning of Life is..."; theMeaningOfLife = 42; std::cout << theMeaningOfLife << std::endl; return 0; }
Essentially, a statement performs an operation of some sort: printing a line of text on the screen, adding two numbers, opening a file, etc. Statements can be very simple, like assigning a value to a variable, or very complex, like making a series of logical comparisons between the outcomes of multiple function calls. For now, it isn't important how these statements work, just get a feel for what's going on in the program. We'll go over all of these different objects, operators and rules and talk a lot more about how statements work in the coming tutorials.
Exercises
- Change the number that is assigned to
theMeaningOfLifeto see how that affects the output. - Change what is typed between the quotation marks " " to provide the user with a different message.
- Back: How to Program C++ with Microsoft Visual C++ 2010 Express Edition
- Top: Game Development and Design Portal
Comments
Feel free to comment, but please be civil and constructive. Inappropriate, inflammatory, and spam-related comments will be deleted.
Last updated October 31, 2011
© 2009-2011 Dave Finch
