Language Selector

1.1 — Structure of a program

A computer program is a sequence of instructions that tell the computer what to do.

Statements and expressions

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. We write sentences in order 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 terminated by a semicolon.

There are many different kinds of statements in C++. The following are some of the most common types of simple statements:

int x is a declaration statement. It tells the compiler that x is a variable. In programming, a variable provides a name for a region of memory that can hold a value that can vary. All variables in a program must be declared before they are used. We will talk more about variables shortly.

x = 5 is an assignment statement. It assigns a value (5) to a variable (x).

std::cout << x; is an output statement. It outputs the value of x (which we set to 5 in the previous statement) to the screen.

The compiler is also capable of resolving expressions. An expression is a mathematical entity that evaluates to a value. For example, in math, the expression 2+3 evaluates to the value 5. Expressions can involve values (such as 2), variables (such as x), operators (such as +) and functions (which return an output value based on some input value). They can be singular (such as 2, or x), or compound (such as 2+3, 2+x, x+y, or (2+x)*(y-3)).

For example, the statement x = 2 + 3; is a valid assignment statement. The expression 2+3 evaluates to the value of 5. This value of 5 is then assigned to x.


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 have your main() function live in a .cpp file with the same name as your project.

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. 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, 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 in the iostream library, which will allow us to write to the screen.

Line 2 has nothing on it, 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 output statement. std::cout is a special object that represents the console/screen. The << symbol is an operator (much like + is an operator) 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.

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 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 an 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 do statements in C++ end 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.7 -- A few common C++ problems

122 comments to 1.1 — Structure of a program

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

  • 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”

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

  • adam

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

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

  • The Leading Man

    ………………………………………… skew you

  • Noha

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

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

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

  • venne

  • 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).

  • chris03653837

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

  • 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


  • 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;

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

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

  • ohhh… every nice i understand!

  • 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;

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

  • 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?

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

  • thanks for every one who do this site thanx much

  • Ali 1

    Thanks for this site owner’s

  • 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!!! :)

  • Maria

    very nice working………..

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

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

  • Xola

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

  • 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).

  • Pankaj Jain

    Hi Alex,

    Quoting from the page :
    "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 use the iostream library. The iostream library will allow us to write to the screen."

    In my opinion, include directive is used to add the header files and not any library . It is used for declaration of function prototype to be used in cpp file so that compiler does not give undeclared identifier/missing declaration error.

    Please feel free to correct me if my understanding is wrong :)


    • Alex

      I’ve clarified the wording a bit. #including the header adds the contents of the iostream header to our program. This provides our program with functionality (an interface) to access the content of the iostream part of the standard library.

      • Pankaj Jain

        Thank you for the clarification Alex . I find these tutorials really good to brush up my basics . I really appreciate all the effort that has been put to make these tutorials :)

  • TKM

    An Exciting Tutorial… Hope to continue

  • Batuhan

    std::cout << "very good tutorial";

  • kausthub

    I want to know when you last updated the lessons with the "Updated" symbol. I have already learnt a lot of lessons so I don’t know if you updated after I learnt.

  • Pankaj Kushwaha

    Thanks alot Alex , for a wonderful and free tutorial.

  • richard harris

    Coming back to c (c++) after years of scripting in PHP/JavaScript etc. First learned it in 1991 and it seems like only yesterday. However, the tools have changed dramatically so this tutorial is a great guide - than you.

  • kobby

    I never dreamt of starting the c++ programming, i always turn myself down. But like a dream, i am beginning to understand Alex’s tutorials…….Tnx for sharing your knowledge, Alex.

  • Odgarig

    I’m really enjoying learning c++ from you.Thank you.

  • Colleen

    Thank you Alex. I am looking for a career cbange and this is exactly what I need for it.

  • vikash verma

    very helpful….thanks

  • Ivxcfvrt

    An expression is ‘A’ mathematical entity

  • newprogrammer

    odd question but do preprocessor directives always need to be in the first lines of the file? what if i wanted to include a library only for a specific function instead of the whole program?

    • Alex

      Preprocessor directives can be used anywhere within a file. However, by convention, #include directives are generally used at the top of a file so it’s easy to see what’s being included.

      I’ve never seen someone #include a file for a specific function before, though I suppose it would be possible.

  • techdummy

    MR ALEX i dont know anything at all and i am a dummy in this field. Do i need to know anything beforehand to get started into the world of programming.

  • Thanks for this awesome post

  • R4Z3R

    What is the difference between header and library!?

    • Alex

      A header file is a file that typically contains declarations meant to be used by other files. Once your programs get to the point where they’re more than one file, header files become quite common.

      A library is typically a collection of reusable header files and pre-compiled code. In order to use the library, you #include the header files in your code and link in the precompiled code.

      I cover header files in lesson 1.9 -- Header files and libraries in appendix A.

  • AD Das

    hey man..these are all using visual c++ but in our school we use turbo C++ where the syntax is much different.. is there anywhere where i can learn using turbo C++ ??

    • Alex

      Most of what is taught in these tutorials should still work in Turbo C++, excluding newer C++ features (e.g. C++11 stuff) and particular features they never implemented full support for.

  • Dyl@n

    Thank you for making this so easy to understand, my only question is that after I finish this whole thing should I be able to write c and c++ without a problem? I just dont want to spend all this time and have the lessons graze over important things later on.

  • Aly Khairy

    When I pasted
    #include <iostream>

    int main()
        std::cout << "Hello world!";
        return 0;

    the cout and main weren’t coloured.

    The code wouldn’t run and gave me an error.

  • george

    What does arbitrary value mean?

    • Alex

      By arbitrary value, I really meant a value that is left to the programmer’s choice.

      I rewrote the definition to make it clearer:

      Variables serve the same purpose here: to provide a name for a value that can vary.

      I think that captures the intent slightly better.

  • george

    Thanks that clears it up :)

    P.s. I love the tutorial

  • Found that you need to declare a function just like a variable before it can be used. So this for example will not work:

    However if you move the test() function to before the main like this:

    It will.
    Just felt if worth noting as I’m used to JS at this point and functions can be called from a any point in the file before or after its "declared", and there are probably more in that same situation.  
    I got stuck for a little minute there just though that someone might have more trouble finding the solution.

  • Great explanation, having a small quiz at the end was very helpful, thanks :)

  • Whao , I love this!!!!@!@ Really want to learn this.

  • i like this to program my magic spells, hah haha he he he

  • Nyap

    I’m 12 years old and I’m interested in learning how to code C++.
    I tested myself on this section. If anyone has the time to check if I got everything right, then plz do so.

    If I did do something wrong, then please explain what the correct answer is in the simplest but most informative way possible. Thanks.

  • Sagar

    my teacher taught me as : #include<iostream.h>
    for : #include<iostream>
    and little bit different from ur hello program,
    is this a different method?  if so, how do I change ur code with that my teacher taught for better understanding of c++.
    Thanks!ur site is a great help..

  • Hesam

    This is my first time of learning cpp, every thing was ok. without any help from anybody, just through your website, I learned to know about visual studio, how to install it and how to start your first lesson. Thank you very much I am so happy about that.

  • Nand

    Dear Alex,

    It is so well explained .. God Bless you ..

    Thanks!ur site is a great help..

  • Why shouldn’t we use
    #include <iostream.h>
      Instead of using
       #include <iostream>
    Is that right?

  • L.a.Inspire

    Thank you very much! Alex .

  • actually i am beginner  ,what are the object and class in c++.

    • Alex

      An object is just another name for an instantiated variable. In object-oriented programming, an object is often used to refer to an instance of a class.

      A class is a user-defined type that bundles data and functions that work on that data together. We discuss classes in chapter 8 onward.

  • DanL

    This lesson states that C++ variables are the same as algebra variables.  Instead it should contain a warning, something like: YO, C++ VARIABLES ARE NOT THE SAME AS ALGEBRA VARIABLES!!  Because they’re not, and thinking that they are can really mess with a new programmer.  Algebra variables don’t actually vary, they are constant, thus it makes sense to "solve for X."  You can think of C++ variables like holders, or containers.  Like a coffee cup is a container for coffee, "int x" makes "x" a container for an integer, but not a particular integer, it can contain ANY integer, and it can change from moment to moment.  I peek at "x" right now and it contains "7", but I check later and it holds "1533".  Now if you use "x" as an integer in your program, you control it -- it doesn’t just randomly change value.  Realize that, although I’m using "x" as an integer here, it could contain almost anything, like words, sentences, a list of all the US presidents, even C++ code, and this is one of the ways that C++ can be very confusing to read and write.  That does not mean that you can plug a quadratic equation into a C++ expression and expect "x" to equal the set of solutions.  Variables in algebra and in programs are things that stand in for other things, but they are maybe more different than they are the same.

    • Alex

      I was trying to draw an analogy between the concept of using a name to represent a value. However, I can see how this might be confusing for people who think that variables in programming are identical to variables in algebra. As you rightly point out, they aren’t. I’ve removed the reference.

  • Nyap

    Hey, I’m sort of confused about libraries.
    a) So you can have libraries inside of libraries? (iostream library inside c++ standard library?)
    b) In section 0.4, when you were talking about linking, you mentioned "the runtime support library". Is this just another name for the C++ Standard Library?

    • Nyap

      also, not really to do with libraries, but when the compiler creates object files, is it basically converting all your C++ code to binary code? If that makes sense?

      • Alex

        Yes. Object files are mostly binary code, but also some additional information required to link multiple object files together into a final executable.

    • Alex

      a) No, when people talk about the “iostream library” they’re really talking about the iostream functionality inside the C++ standard library.
      b) The runtime support library is the same thing as the C++ standard library. I’ll update the language in lesson 0.4.

  • Frank

    Hey Alex, where can I get the list of codes and thier corresponding functions.

    • Alex

      What do you mean by “codes”?

      • Stormie

        I think he means the text such as "std", "int" & "cout". I have been following the tutorial (which is very helpful) and one of the first things I thought of needing is a reference card or glossary of abbreviations. Would this be useful? Or is it much more complicated than that and the same "code" (not sure what the term would be) changes dependent on the instance it is used in?
        Nice one Alex for these tutorials and (continuing!)responding to comments. I learned almost as much from the comments as from the tutorial ie how not to do things or why some people may do things differently and an initial understanding of what the pros and cons might be.

        • Alex

          If you’re the type of person who likes to write notes while learning so you can reference back to things you’ve already learned, then by all means, yes, create a list as you learn.

          At some point I may create a glossary, but it doesn’t exist currently. :(

  • Ishwar Singh

    Its so helpful … Thanks to u Alex

  • Benedikt

    #include <iostream>
    using namespace std;

    void cout()

    int main()
        std::cout << "Hello World" >>

    I work with a clean map and moust create my own main.cpp
    and It works normaly with this Code but I got a error and I dont know why it doesnt work can you help me?

    • Alex

      Two questions:
      1) What error did you get?
      2) Did you create a project/solution for this code, or just a .cpp file outside of a project?

  • Benedikt

    I just cant find the good damm misstake, I know its a hard way to good create a calculator but I try some new things like if and else if it was needed i can write the same stuff on english,pls help me

    #include <iostream>
    using namespace std;

    int main()
        int zahl1;
        int zahl2;
        cout << "Bitte eine beliebiege Zahl eingeben!" << endl;
        cin >> zahl1;
        cout << "Danke Sie haben " << zahl1 << "eingegeben" << endl;
        cout << "Geben sie nun" << zahl2 << "ein" << endl;
        cin >> zahl2;
        cout << "Danke sie haben" << zahl2 << "eingegeben" << endl;
    cout << "wollen sie mit den Zahlen 1 und 2 Rechnen?" << endl;

    char antwort = ‘ ‘;  

    cout<<"Ja (j) /Nein (n): ";

    if (antwort == ‘j’)  
    cout << "Du hast ja gewählt" << endl;
    cout << "waehlen sie nun ihr Rechenzeichen" << endl;
    cout << "+,-,*,/" << endl;
    if (cin >> "+")
        cout << "zahl1 + zahl2" << endl;
    else (cin >> "-");
        cout << "zahl1 - zahl2" << endl;
    if (cin >> "!= +,-")

    char antwort  = ‘ ‘;

    cout << "(*),(/): ";
    if (cin >> ("*"))
        cout << "zahl1 * zahl2" << endl;
    else (cin >> ("/"));  
        cout << "zahl1 /zahl2" << endl;

        return 0;


    • Alex

      It looks like there are quite a few mistakes in there. Instead of debugging this, I’d like to suggest you read a bit further in the tutorial series and then come back to this program again.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter




seventeen + 4 =