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

280 comments to 1.1 — Structure of a program

  • Pork and Beans

    Thank you very much for these very informative and easy to read tutorials, Sir.

    After reading through the comments, the vast majority of which were beyond me, I am still left wondering if there as a reason that you left out the "endl;" command in the above section entitled "Taking a Look at a Simple Program".  The user "J" touched on this instance and I am hoping to, as a beginner, resolve the mystery.  I understand what "endl;" does, but by omitting it from your example above I have become confused.

    I look forward to your reply, and to continuing through these lessons.

    Have an excellent day.

    • nascardriver

      Hi Pork and Beans!

      You don't have to be confused, it just doesn't jump to the next line.
      If you're only planning on printing one line (like it's the case in the sample) you don't necessarily need to insert a new line. Although the new line can be omitted for small code like this it shouldn't be for forward compatibility, because if you decide "hey, actually I want to have another line" you'll have to go back to the old line and modify it before you can print the next line (there are ugly ways around this).
      I assume Alex didn't want to use std::endl to keep the program as simple as possible.

      • Pork and Beans

        Thank you, Nascar Driver!

        I have found that it is best to simply forge ahead.  I have planned on taking these tutorials a second time.  They are very exciting and are put together better than I could have hoped.

        I appreciate your input.  🙂

    • Alex

      nascardriver nailed it. The example used to have std::endl, but then I had to explain what std::endl was, and that was both a distraction and creating lots of questions. So I removed the std::endl, because it's not necessary for this example, and talk about it in more detail in a lesson focused around the topic of input and output.

      • Pork and Beans

        Understood.  Thank you so much for providing these lessons - they are exactly what I was after.  I am very excited to continue learning the content you have shared and am very pleased that the community is alive here.  I will try to keep my questions to a minimum, but if there is anyone there that could possibly mentor me, I would love to stay in contact.  Thanks to you, Alex, I am crafting my own C++ programs - simple, albeit, but nevertheless, I am learning the concepts!  🙂

        Have an excellent evening.  Your work is greatly appreciated.

  • Zach

    I just wanted to let you know how amazing of a person you are for creating and maintaining this insanely useful website for over 10 years. These are such high quality written tutorials especially for their non existent price!

  • Sahil

    Hi Alex,

    I've just started going through your tutorials, and I think they are great. Thanks a lot for that 🙂
    There's one suggestion/question however:
    In section "Taking a look at a sample program", when you're explaining Line 3, should it be "Line 3 defines the main ..." instead of "Line 3 declares the main ..." ?
    I'm not a C++ pundit, but this question arises from the C knowledge that I have.
    Please correct me if I'm wrong.


  • J

    Hello, Alex. I am using Microsoft Visual Studio as my IDE. In the previous lesson the 6th line of HelloWorld.cpp was

    std::cout << "Hello World!" << std::endl;

    What does << std::endl; do? (To be clear, I understand that endl injects a end-line character - I did google it - but I don't understand why this is useful.)

    Also, is there a way for me to make the code I paste in these comments appear well-formatted like your does?

    • Alex

      It moves the cursor down to the next line, so if you output a second bit of text, it will be on the subsequent line, not the same line.

      You can make your code look like mine by putting the inside [code] [/code] brackets.

  • Robert

    Typo in the 'Syntax and syntax errors' section. Search for this line:
    "This is telling you that you have an syntax error on line 6".

    It should say 'a' syntax error, not 'an' syntax error.


    Thanks for these tutorials!

  • I definitely really liked every part of the information about C++ you have provided and I also have you saved to fav to look at new information in your site.

  • Dan the African

    Finally a actual good website that's updated, now I can learn and my parents can love me. 🙂

    Overall good lesson, learnt a lot

  • #include<iostream>
    using namespace std;
    int main()
      int a;
    why these program is showing error

    • ashutosh

      return the value
      return(0); before the last line

      • Maxixxx

        I don't think the return statement is necessary. The correct code:

        Explanation: assign the value to the variable first, then display it.

        • nascardriver

          Hi Maxixxx!
          Although the return statement in main can be omitted, it never should be. main is declared to return an int, so you return an int.
          The problem with the original code is that the << operator will be executed before the = operator is.

    • Alex

      It's a precedence issue. << takes precedence over =, so the expression parses as (cout<<a)=5, which makes no sense.

    • Porkinns

      It's a syntax error (or like Alex said precedence error)
      you can either say :




    • sonia

      we cannot use the expression a=5 in the output it should be std::cout<<"a";  
      a=5; can be declared before that.

      • Alex

        You actually can, so long as it's given the correct precedence.

        Because (a = 5) is parenthesized, it evaluates first, and evaluates to the value of a (which is 5). So this statement both assigns the value of 5 to a and prints that value to the console.

        Generally speaking, you _shouldn't_ do this because it's confusing (doing separate statements is better) but you _can_.

  • Frank

    Great tutorial thank you very much!

  • syad abdul

    is return o ; is imp when writing 'int main' can we use void main instead and no need to right return 0 '.

  • Umair

    In visual studio 10, I made 2 console projects. One was empty and one wasn't. I created new .cpp file in empty project and put same code in both. But the non-empty {which already have 2 header files and one .cpp file (named as stdafx.cpp)}.
    For non-empty one this error came:

    Error    2    error C1010: unexpected end of file while looking for precompiled header. Did you forget to add '#include "StdAfx.h"' to your source?    c:\users\umair\documents\visual studio 2010\projects\2\2\2.cpp    21

    While the empty one is running well.
    What is the problem here.

    • Alex

      The non-empty one is using precompiled headers (I don't know about the empty one). Make sure #include "stdafx.h" is the first line of any .cpp file and you'll be fine.

  • Person 1

    Why you no use..

    using namespace std;

    • Alex

      Because it increases the chance of a naming collision significantly, and it's considered a bad practice to do this globally. I discuss this more in chapter 4.

  • LTC

    I made a realy cool program that crashed my IDE

  • Max

    Hey Alex, here is a piece of code that i seem to have quite a bit of trouble with. There is no specific intention to this program other than just practicing, but i still seem to be dedicated to get this to work.

    Anyways, my problem is that when i run the code, the output displays "The password is correct" even when i type a value that is not equal to the variable "pass". For example, if i type the letter e, it will still show "The password is correct" and the following lines will appear as well, but instead of asking me for an age, it has a pre-selected age which is a completely irrelevant number. In this case, it was -858993360. I want the program to only run if the variable pass matches the value entered. How would i make this work?


    #include "stdafx.h"
    #include <iostream>

    int main()

        std::cout << "Please enter the password" << std::endl; // asking for password

        int pass = 123456789; // gave a value to the password

        std::cin >> pass; // user inputs the password
            if (pass == 123456789) { // if 123456789 is entered, print "The password is correct"

                std::cout << "The password is correct" << std::endl;

        } else { // if anything else is entered, print "The password is incorrect"

            std::cout << "The password is incorrect" << std::endl;


        std::cout << "What is your age?" << std::endl; // asks for age
        int age;
        std::cin >> age; // gives the variable age, an input
        std::cout << "Your age is " << age << std::endl; // prints the age
        std::cout << "In 100 years, your age will be " << age + 100  << " years old" << std::endl;

        return 0;

    • Alex

      You're initializing variable pass with value 123456789. You're then asking the user to override that with a new value. But if the user enters an invalid input, the existing input is not overwritten, so the value of pass does match 123456789.

      If you're going to initialize pass, initialize it to 0.

      I talk about how to handle error cases (such as when you're asking for an integer and the user enters a letter) in a future lesson. I think in chapter 5.

      • Prince

        it is working fine Alex .  i have entered 'e' it says "The password is incorrect".
        but you are saying that it is happening due to invalid input ,incase of invalid input ALSO how the program is working as desired?

        • Alex

          Yes, 'e' is not a valid value for an integer variable, so the user input fails. To deal with this, you'll have to handle the invalid input. I discuss how to do this in a future lesson (I think in chapter 4 or 5).

        • prince

          if a user input fails then the default value returned to that variable is'0'. it just the case in codeblocks.
          reference: for above code when i inputted 'e' it said password is incorrect and printing value of pass it showed '0'.

  • Thomas

    Hey man, thanks a lot for these tutorials. I really want to get into computer programming and I hope these tutorials will guide me to that.

  • DanielLearnCPP

    Is this guide up to c++11 and 14 standard´?

  • Hello, Dear Sir.
    Thanks For Your Teaching This is a good Website

  • Gurdeep Singh

    Why instead of puting line [using namespace std;] at 2nd place we used [ std::] before cout?

    • Alex

      Because "using namespace std;" is a bad programming practice. We discuss why in chapter 4. It's better to use the explicit std:: prefix where you can.

      If you're going to use a using statement, at least put it inside any function that needs it rather than in the global namespace.

    • HarsshChaudhry

      its completely correct you can use it without no problem

      • SirElismyer

        It isn't that it is illegal, just bad practice. It makes it significantly more possible that you will accidently call a function from the wrong library (especially if you are using custom libraries that aren't in the standard). Its a bad habit and you shouldn't do it.

  • Sieun

    Alex, you are an awsome teacher

    • Alex

      Thank you. If you find anything in the tutorials that isn't clear or doesn't make sense, please bring it to my attention so I can make it better. 🙂

  • Michael


    Thanks for these tutorials.  The last time I tried computer programming, it was on a TRS-80 Model 1.  The books I used to attempt this seemed to be written by people who had only a little more experience than me.  This is so much better.

  • Karlosmi

    Dear teacher, thank you for maintaining this site.  Please, tell me, what is the secret to become a good programmer like you?...; and, how young a student needs to be in order to learn this stuff?

  • My dear c++ Teacher,
    Please let me just two comments:
    Simple program does not include #include "stdafx.h" for when compiler is visual studio.
    Also program omitting semicolon is compiled by visual studio but #include "stdafx.h" is also omitted!
    With regards and friendship.

    • Alex

      I've added another reminder to #include "stdafx.h" for Visual Studio users, but it's up to you to remember to do this. Later examples in this tutorial do not include this reminder, since it is compiler specific.

      I've reconfirmed that the program missing a semicolon does not compile in Visual Studio 2015. I'm not sure why you might be seeing something different.

  • Zuhayer

    Hey Alex
    So whenever I run the program on Code Blocks it displays this error message -
    Target uses an invalid compiler; run aborted

    How do I fix this? ;-;

    • Alex

      It sounds like your compiler has not been set up correctly for your operating system. Make sure you've downloaded the correct version of Code::Blocks and try reinstalling.

  • Abheet

    "Every C++ program must contain a special function called main."
    You say that every program in C++ must use the main function, so why isn't the main function always stored in the program before hand, so we don't have to waste a couple seconds typing it over and over again for every program we write?

    I mean, there must be a reason why we must write the same command every time..? (Right?)

    • Alex

      Many IDEs will pre-create an empty main() function for you, so you don't have to type:

      Because the contents of main vary per program, the body of main is typically left empty to start (excluding the return 0).

  • cool_boy

    What is the meaning and use of " std:: ". This wasn't used in  codes in different websites.

  • john

    what does he mean by " have your main() function live in a .cpp file"??

    • Alex

      I mean put the code for your main() function in a file named xxx.cpp, where xxx is either main or the name of your project. That way it will be easy to find where your program starts later.

  • seth

    So i am really enjoying this website me and my friends are planning on making a game called truck jumpers. I am also a music maker but, I have a question, will all this code work on eclipse because i only have a mac. thanks!


    I have just started to learn C++.
    What I've learnt till date is we use <iostream> which contains everything needed for input/output.
    Then also we need to type 'using namespace std' OR std::cout otherwise the code throws an error.

    So my question is what is the necessity of using this namespace or std::cout if everything is there in <iostream> for cout, cin etc..

Leave a Comment

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