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.


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 console.


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.


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 console 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 console.

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. Reminder to Visual Studio users, you will need to ensure precompiled headers are turned off, or else add #include “stdafx.h” (or #include “pch.h” if using the latest versions of Visual Studio 2017) to 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.


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

2) Show Solution

3) Show Solution

4) Show Solution

1.2 -- Comments
0.11 -- Configuring your compiler: Warning and error levels

281 comments to 1.1 — Structure of a program

  • Akshit S

    So after execution of our program, compiler returns a value to the OS indicating whether or not our program was successfully compiled and executed. But, here we are already specifying a return value (in the above case, '0'). We forcefully want our compiler to tell our OS that there wasn't any error in our program. Shouldn't this job be handled by compiler itself, instead of user specifying a return value?

    • Alex

      At the end of execution of our program, the program returns a value to the OS (not the compiler).

      Typically, things happen in this order:
      * Programmer writes code.
      * Programmer uses compiler to compile code into an executable. (The compiler's job is done at this point)
      * User runs executable.
      * Executable returns a code to the OS to indicate whether the executable ran successfully.

      The compiler generally won't even be running when the executable is running (unless you're debugging).

  • Xola

    Hi how can I gt the minGw compiler, currently m using turbo C++
    It's quite tricky to work with.

  • Amir

    Hello.I am From Iran and in my University I Learned the Python very well. but dont teach the c++.
    this Site is very Special and very good.
    thanks for all your difficulty.

  • Sind

    int x;
    This tells the compiler that x is a variable

    Does this mean, memory is allocated for variable x when variable x is declared?
    What exactly is the difference between declaration and definition?

    • Alex

      Really good question about the difference between declaration and definition. The easiest way to think about it is as follows:

      * A declaration introduces an object object (function, variable, etc...) and it's type. A function prototype is an example of a declaration. A declaration is enough to satisfy the compiler. You can have multiple declarations for the same object.

      * A definition actually defines that object. A function with a body is an example of a definition. A definition is needed to satisfy the linker. There can only be one definition for an object.

      In many cases, a single line serves as both the declaration and definition. For example, "int x" is a declaration AND a definition.

      Memory is allocated at the point of instantiation, which is when the object (variable) is actually created. This point can vary depending on where the variable is. For example, if a variable lives inside a function, the variable won't be created (and memory assigned) until that function executes.

      • John Zulauf

        First, remember that the declaration is purely semantic. You have a name that logically associates with a type and a value.  What the compiler does will vary. See the section on build configurations above.  

        For "debug" builds, variables local to a function are typically given memory when first assigned a value.  That memory is only present for as long as the variable is in scope (i.e. code is executing within the {} the variable was defined in, and then is subject to reuse.

        For release builds, typically the compliers optimizer is enabled -- and all bets are off.  Local variables (those that are part of a function) are not guaranteed to have *any* memory is allocated. Depending on how x is used, x may only ever exist inside a CPU register and never be stored to memory.  Other optimizations might collapse all logical operations on x to a logically equivalent set of instructions that don't ever have any of the values that x would logically take on.

        Debugging release builds can be a serious pain, and bugs that only exist in release builds are among the most pernicious.

  • Maria

    very nice working...........

  • Joseph H

    I just started with the tutorial yesterday and completed my first program! I am in HS and want to learn c++ because I want to be a computer programmer! Thank you this is all good and if you have any tips for me or other codes I can learn online please comment!!! 🙂

  • Ali 1

    Thanks for this site owner's

  • thanks for every one who do this site thanx much

  • plus minus

    Why we need operators?

    • Alex

      Operators provide a convenient and concise way for us to get different things to interact.

      Take for example "3 + 4". The + operator adds 3 and 4 to produce the result 7.

      With cout << "Hello world", the << operator takes "Hello world" and gives it to cout to print on the screen. Without the << operator, the compiler wouldn't know whether "Hello world" was meant to interact with cout or something else.

  • ballooneh

    Hey there!

    I am wondering what "int" does in "int main()".
    What does it do and when do i use it?

    I also read somewhere that you can use "void" instead of "int".
    What does "void" mean and what does it do?

  • pmc24

    Consistency issue.

    For beginners, the move from

    using namespace std;



    might be confusing.

    Hence I suggest amending the example code accordingly, or leaving a note at the end of the tutorial highlighting the interchangeability feature of the two.

  • betefeel

    I started doing some things on my own hehehe


    int main()

    int x;
    int y;
    int d;
    int f;
    x = 5;
    y = 5;
    d = x + y;
    f = d + d;

    using namespace std;
    cout << x + y << endl;
    cout << f << endl;
    return 0;

    • Umair

      I think this one is more appropriate:

  • ohhh... every nice i understand!

  • Homesweetrichard

    On mac (xcode) there will be one error if you follow it exactly as shown on this page. Instead use this one


    int main () {
    using namespace std;
    cout << "Hello world!" << endl;
    return 0;


    Even if you have ignore white space on it will still err. So do not give "{" its own line thats bad programming on xcode. it took me a week to figure that out, because i was wondering why it wasnt "build & run" so i started to play around with spacing, after i had already asked 10 different sites why didnt this code work, turns out it does, just requires a certain spacing requirement. My guess is you cant use "{}" without telling it why its there. thats probably a bad explaination or wrong explaination.

  • cubbi

    Endl is a special symbol that moves the cursor to the next line
    This is incorrect. The special symbol that moves the cursor to the next line is '\n'. Abuse of std::endl for this purpose is bad practice which leads to inefficient programs.

    • Alex

      I updated the wording to be more precise:

      Endl is another special object that, when used in conjunction with cout, causes the cursor to move to the next line (and ensures that anything that precedes it is printed on the screen immediately).

      You are correct that overuse of std::endl can cause performance issues in cases where flushing the buffer has a performance cost, such as when writing to disk. I made notes of this in lesson 13.6 -- Basic File I/O, where I talk about buffering and flushing in more detail.

  • Plz explain using namesapace std; in more understandable manner alex sir.

    • Adam Sinclair

      using namespace std; is basically using "std" throughout the entire code.

      Instead of writing std::cout:: << "Hello World!" << std::endl; or something like that. You won't have to include all that "std::" if you have

      using namespace std;

  • Met

    very good website this. thanks to the Admin of this website and the people who made this possiable to us. Great lessons

    thanks again


  • chris03653837

    you gys need to stop smoking bad weed, the code is fine.

  • IsNe

    When i code i place the:

    at the top

    it still works, isn't that more convinient? or is there a reason for placing it inside each and every function

    • Alex

      It's more convenient perhaps, but also more dangerous. If you put the using namespace std; statement at the top of your code, it applies to everything in the file. This increases the chance of naming collisions.

      Generally, it's better to either put the using statement in each function that needs it, or call cout directly using the scope resolution operator (e.g. std::cout).

  • venne

  • vishvesh

    It would be good if you could explain the difference between functions and methods.

    • Alex

      A method and a function are essentially the same thing. In C++, we usually use the term function when the function is independent of an object, and method (or more commonly, member function) when the function is part of an object/class.

  • Ray

    Wow ur teaching or tutorial here is much better than my teacher. I'm currently studying engineering with c++ as a module but till now i nvr knew the true meaning of 0 at the return 0.

  • Noha

    Is there any explanation about the structure of Standard Template Library (STL)in this site?

  • The Leading Man

    ................................................ skew you

  • I have Visual C++ 2005 Express Edition,
    but my lines aren't numbered. Why?

  • adam

    if "cout < < "Hello world!" << endl;" is a statement and "<<" is an operator what is "cout" a command?

  • adam

    is an expression a type of statement?

    • I'm not quite sure how to answer that.

      In most cases, and expression is PART of a statement. For example:

      "2 + 3" is an expression that evaluates to 5. x = 2 + 3 is an assignment statement that assigns the result of evaluation 2 + 3 to variable x.

      It is possible to have a statement that consists only of an expression. For example, the following is allowed:

      This expression evaluates to 5, but since the result is not used anywhere it is just discarded.

  • parasyte

    hey man very nice though you wrote " would like to use the iosteam library." in the first paragraph after
    "Taking a look at a sample program"

  • Thanks for this part of the tutorial. I found this section really helpful.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]