The Parts of a C++ Program: Functions, Variables, Statements and More

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.

Libraries and DLLs: A set of static libraries known as the standard library, which is part of the C++ standard, is included with every C++ compiler. Additional static libraries, like the Win32 libraries for creating Windows applications, may be downloaded and installed to create programs utilizing features from these libraries. Programers use static libraries to create the program during development. End-users don't need to worry about what static libraries they have installed on their system. In contrast, DLLs, or dynamic-link libraries, are used in a similar way by developers, but must also be downloaded and installed by end-users who want to use programs that depend on features from that library. That's why Windows users have to download and install DirectX to play Windows PC games.

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.

The Myth of Intelligent Machines: Although many people act as though computers are very smart, they are in fact quite stupid and literal. For example, no computer is smart enough to figure out what you mean if you say one thing but mean another. (Ever deleted anything by accident?) A good way to think about computers is to compare them to a row of dominos. If instruction A tells them to do X, they will do it without thinking about it or understanding the consequences, just as when you knock over one domino, it knocks over the domino next to it. Computers are literally as intelligent as a row of dominos. Any 'intelligence' that you see displayed by a computer (for example, Google's 'did you mean...?' search suggestions) is the result of a long series of instructions created by a programmer.

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:

The Meaning of Life is 42

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.

Syntax: Syntax is a fancy word for 'rules' when it comes to language. Every language has its own syntax, or set of rules. In this way, C++ is no different from English or Japanese. With spoken and written languages, however, there are usually exceptions, or ways to bend the rules. With programming languages there are no exceptions: if your program doesn't follow the rules of the language, you'll get a 'syntax error' and your program will fail to compile.

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;
}
Angle Brackets vs. Quotation Marks: When #include directives enclose file names in angle brackets these generally denote files that come bundled with the compiler that the compiler is already aware of. For example, MSVC++ comes with the iostream file and knows where to find it so all you need to do is tell it to fetch it. If you want to include custom files that you've written yourself, you generally need to enclose the file name in quotation marks and include the file extension (for example, #include "MyHeader.h" for a custom header file). In this case, you're telling the preprocessor that you've written a new file that it needs to go look for.

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;
}
Strong vs. Weak Typing: C++ is a strongly typed language. What that means is: if you want to use a variable, you have to name it and tell the compiler what type of variable it is before you use it. Some languages don't have this requirement: the compiler or interpreter will simply pick a variable type that matches the value you assign to it at the time it is translated. Being a strongly typed language might seem like an inconvenience at first, but it's actually a good thing: it forces you to think and state your intentions clearly and it makes it easier for the compiler to find and catch logical errors in your program. In small scripts, that's not such a big deal, and the language can get away with being convenient over being strict. C++ is used for huge, critical applications and can't afford those kinds of luxuries: it's not a stretch to say that sometimes lives are at stake, so it doesn't hurt to be a little more careful about how we code.

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;
}
Arguments vs. Parameters: When you define a function in a program, you give it a parameter list; that is, a list of variables that it needs to perform its function. When you use the function, you pass in a list of arguments. These arguments must match the parameters for your function to work. Take the example of getting into a bar. At the door, the bouncer asks for your id. His function is to verify your age; to do that, he has two parameters: your age, and proof that you are who you say you are (in this case, a photo). If you pass him your driver's license, your arguments are the age on the license, and your picture. Assuming you're old enough, and the picture looks like you, you're in. You have passed arguments that match the parameters. If you try to get in using a bar of soap and a cheese grater, your arguments won't match the parameters and the function will fail. (If you pass him a fake license, or someone else's license, the bouncer will use his internal logic to determine the result of your ruse. Maybe you'll get in, maybe you won't. It depends on how good his AI is.)

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:

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.

cout: cout stands for character output. It is often translated to console output. It is generally pronounced 'see-out'.

Exercises

  1. Change the number that is assigned to theMeaningOfLife to see how that affects the output.
  2. Change what is typed between the quotation marks " " to provide the user with a different message.

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

SUPPORT TRUANCYFACTORY