- Learn C++ - https://www.learncpp.com -

1.1 — Structure of a program

A computer program is a sequence of instructions that tell the computer what to do. Programs are typically composed of 3 basic elements: expressions, statements, and functions.

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, which we use 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 often (but not always) terminated by a semicolon.

There are many different kinds of statements in C++. Here are a few example statements that you might find in a program:

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. All variables in a program must be declared before they are used. We will talk more about variables shortly.

x = 5; is a statement that assigns a value (5) to a variable (x) so we can use that value later (which we do, on the next line).

std::cout << x; is a statement that outputs the value of variable x (which we set to 5 in the previous statement) to the screen.

Expressions

The compiler is also capable of resolving expressions. Expressions specify a computation to be performed. For example, as children we all learn that 2 + 3 equals 5. In programming, we say that 2 + 3 is an expression that evaluates to the value 5.

Here are some examples of different types of expressions:

You’ll note that expressions can contain literal values (such as 2, which evaluates to 2, or “Hello, world” which represents text). Expression can also contain variables (such as x, which evaluates to whatever value variable x is holding), mathematical operators (such as +, which does addition), and function calls (not shown above, but to be discussed shortly).

For example, x = 5 (no semicolon on the end) is a valid expression that assigns the value of 5 to variable x.

Expressions can not be compiled by themselves, as they are meant to be used inside statements. For example, if you were to try compiling the expression x = 5, your compiler would complain (probably about a missing semicolon).

Fortunately, it’s extremely easy to convert an expression into an equivalent statement. An expression statement is a statement that consists of an expression followed by a semicolon. Thus, we can take an expression (such as x = 5), and turn it into an expression statement x = 5; that will compile.

It’s interesting to note that some statements may contain multiple expressions. We’ll see examples of these in future lessons.

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 student’s grade. We will talk more about functions later.

Helpful hint: It’s a good idea to put your main() function 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, you could 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, you’d probably want to include a sound library and a graphics library.

The C++ core language is actually very small and minimalistic (and you’ll 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 they’re 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, expressions, functions, and libraries are, let’s look at a simple “hello world” program.

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 text 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 it’s a statement because it ends with a semicolon), and it is an expression statement. std::cout is a special object that represents the console/screen. The << symbol is an operator (much like + is an operator in mathematics) 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, we’re 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.

(Note: If you want to compile this program yourself, you can. However, Visual Studio users will need to add #include “stdafx.h” as the first line of any C++ code file written in Visual Studio)

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 many types of statements must end in a semicolon.

Let’s see what happens if we omit the semicolon in the following program:

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 a syntax error on line 6: You’ve 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 doesn’t notice until the next line.

Syntax errors are common when writing a program. Fortunately, they’re 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 are statements in C++ often ended with?
4) What is a syntax error?

Quiz Answers

To see these answers, select the area below with your mouse.

1) Show Solution [1]

2) Show Solution [1]

3) Show Solution [1]

4) Show Solution [1]

1.2 -- Comments [2]
Index [3]
0.7 -- A few common C++ problems [4]