1.1 — Structure of a program

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


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 often 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. 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 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 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, 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 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 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 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.7 -- A few common C++ problems

182 comments to 1.1 — Structure of a program

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

  • My dear c++ Teacher,
    Please let me ask: are only statements terminated with semicolon?
    In other words: is everything terminated with semicolon, statement?
    With regards and friendship.

    • Alex

      Statements are terminated with a semicolon. However, not all statements need to be terminated. So no, not everything is terminated with a semicolon.

      If you want more detail, there’s a good discussion on Stack Overflow.

      I’ve softened the wording in the lesson to indicate that statements are often terminated by a semicolon (not always).

  • Mustafa

    Will this tutorial go over gui at some point?

    • Alex

      Not currently. Unlike some more modern languages, C++ does not come with any built-in functionality for doing GUIs. This tutorial focuses mainly on core language mechanics.

      The good news is that there are plenty of 3rd party libraries that you can install and use to create your own GUIs. By the time you finish this tutorial, you’ll be well prepared for installing and using those.

  • N

    Hello there Alex! I wonder if can I can use all your materials (with your permission of course) to help my student learn the C++ PL (those explanation where very simple and easy to understand [minus the technicalities I found in my Programming Books) by the ways I am an IT Instructor and one of my subject is (incidentally) C++. I will also mention this great tutorials of yours to my student. Thanks! Keep up this awesome work!

  • Devil Hand

    Is iostream a library in itself or a part of the c++ standard library?
    Or it is a header file?(If yes then what does header files actually mean?)
    And what is the difference between header files and libraries?
    P.S. The tutorials are amazing amazing amazing. Already learned a lot!

    • Alex

      iostream is a header file that is part of the C++ standard library. We talk about header files in detail later in this chapter. Libraries are typically precompiled code that you can link into your program. I talk about libraries in appendix A.

      • Devil Hand

        But in one comment you said that cout and endl live in the iostream library….
        It’s confusing!

        • Alex

          Thanks for clarifying your concern -- I think I misunderstood what you were asking. Let me see if I can clarify further.

          The C++ standard library is internally divided into different areas, each of which is also informally called a library even though it’s just part of the standard library. So when we talk about the iostream library, we’re really talking about the part of the C++ standard library that contains C++’s streaming input/output functionality. That functionality is accessed by including the iostream header in your programs. Does that make sense?

  • GEScott71

    Thanks Alex, for the tutorial and the comments section - I’m learning a lot from the comments and your replies too.

  • Mahesh

    Thanks Alex.. Great Work !!

  • homayou

    thanks a lot i love it

  • Aar Jay

    Alex. Thanks for writing these great tutorials. Just started learning. So here goes a silly question:
    Does it matter if the output operator is written on a particular side of the object std::cout, which represents the screen? I mean will it be syntactically correct to write a statement like this: "Print this" >> std::cout;

    • Alex

      Yes, it does matter. Operator << is used for output, whereas operator >> is used for input.

      • Aar Jay

        Thanks for replying. But sorry I erred in writing my question. I meant say that I will still use the output operator << with std::cout, but can I write it on left side of std::cout? Like this statement: "Print this to screen" << std::cout;

  • chuks

    Lovely. I just flow with the explanation. So easy!

  • Hey Alex, First of all, Thanks for tips and tutorials, really enjoyed.
              second, i was just confused on the part

    1. is the std::cout<<Hello Alex << std:: endl; a newer way of putting just  cout << Hello Alex << endl; ? what’s the recommended one?

    Thank you .

    • Alex

      It’s better to use the std:: prefix. It’s less ambiguous, as it makes it clear exactly what you’re referring to, so the compiler doesn’t have to infer your intent.

  • Deepu

    Under the functions paragraph

    Helpful hint: It’s a good idea to have your main() function live in a .cpp file with the same name as your project.

    I didn’t grasp by what you meant by that sentence,perhaps you could elaborate with an example.

  • sajib saha

    in turbo c++ there is no need to enter

    using namespace std; or std:: before cout  

    and #include"iostream.h" replaces "iostream"

    and it runs I correct?

  • mostafa karam

    #include <iostream>

    int main()
       std::cout << "hello world!";
       return 0;
    .i did print the same code but it is still not working
    and then i did print this code
    #include <iostream>

    using namespace std;

    int main()
        cout << "hello world";
        return 0;
    and it did work .. is it because i use visual studio 2012 or what

  • Tim Palmer

    You said "the compiler resolves this expression" Does this mean that for example

    would be simplified to

    after compiled? I mean rather than at runtime.

  • Raul

    WOW, amazing website. I’m new to C++ and I’m really taking my time reading each chapter and the viewer’s comments. I installed Visual Studio 2015 and Code::Blocks and I like the later better. I’m running both at the same time to see the differences. Visual Studio 2015 takes a little longer to compile than Code::Blocks. So far I have not run into any issue, but I’m liking Code::Blocks better. I’m hoping all chapters have Code::Blocks examples if I run into an issue 🙂

    I remember using Visual Basic back in college in 2000, had to take it because of my major. I also used Tiny C Compiler, HTML Kit and some other freeware programs at that time, but I can tell things have changed, haha.

    Great to have a quiz at the end! (Y)


  • Is resolving of an expression performed at compile time? Or it is performed at run time also.
    I am thinking of these situations as per my examples below

    Compile time

    Run time

    Note: Value of a and b are taken from console at run time.
    Please correct me if I am wrong.

    • Alex

      Yes, some expressions can be resolved at compile time. These are called constant expressions. I talk a more about this in chapter 2.

  • Sahal

    What is the difference between DEBUGGING and CORRECTING SYNTAX ERRORS???

  • BeaverFeaver

    This was really helpful Alex, thanks :).

  • Benedikt

    thanks for the answer, and I just try some new things because i would try something, so i read more and would try it again

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

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

  • Ishwar Singh

    Its so helpful … Thanks to u Alex

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

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

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

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

  • L.a.Inspire

    Thank you very much! Alex .

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

  • Nand

    Dear Alex,

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

    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.

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

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

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

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

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

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

  • george

    Thanks that clears it up 🙂

    P.s. I love the tutorial

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

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

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

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

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

  • Thanks for this awesome post

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

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

  • Ivxcfvrt

    An expression is ‘A’ mathematical entity

  • vikash verma

    very helpful….thanks

  • Colleen

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

  • Odgarig

    I’m really enjoying learning c++ from you.Thank 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.

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

  • Pankaj Kushwaha

    Thanks alot Alex , for a wonderful and free 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.

  • Batuhan

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

  • TKM

    An Exciting Tutorial… Hope to continue

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

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

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

    • I’m not sure what the problem is with that. Am I missing something? 🙂

      • sorry188

        iosteam should be iostream. It is missing an “r”.

        [ Wow, I can’t believe I didn’t see that. Fixed now! Thanks all. -Alex ]

      • ghost

        using namespace std; is in the wrong line
        it should be in the main header before int main( )

        • Alex

          No, it shouldn’t. If it’s in the main function, the scope of the statement only applies to the function (which is good). If you put it in the main part of the program, it applies to the entire file, which is generally considered poor form (and could lead to naming collisions).

        • Ganesh

          If you use iostream instead of iostream.h,you should use the following namespace directive to make the definition in iostream available to your program.using namespace std at the beginning of the program is bit lazy and potentially a problem in large projects.the preferred approaches are to use the std:: qualifier or to use something called using declaration to make just particular names available.for example using std::cout.

      • Gilbert

        I’m not sure if it differentiates between C++ Compilers or not but I’m using Visual C++ and my program will not compile unless the using namespace std; is outside of the main function

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

Leave a Comment

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