Search

1.1 — Structure of a program

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

Statements

The most common type of instruction in a program is the statement. A statement in C++ is the smallest independent unit in the language. In human language, it is analogous to a sentence. 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.

Expressions

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.

Functions

In C++, statements are typically grouped into units called functions. A function is a collection of statements that executes sequentially. Every C++ program must contain a special function called main. When the C++ program is run, execution starts with the first statement inside of function main. Functions are typically written to do a very specific job. For example, a function named “max” might contain statements that figures out which of two numbers is larger. A function named “calculateGrade” might calculate a student’s grade. We will talk more about functions later.

Helpful hint: It’s a good idea to put your main() function in a .cpp file named either main.cpp, or with the same name as your project. For example, if you are writing a Chess game, you could put your main() function in chess.cpp.

Libraries and the C++ Standard Library

A library is a collection of precompiled code (e.g. functions) that has been “packaged up” for reuse in many different programs. Libraries provide a common way to extend what your programs can do. For example, if you were writing a game, you’d probably want to include a sound library and a graphics library.

The C++ core language is actually very small and minimalistic (and you’ll learn most of it in these tutorials). However, C++ also comes with a library called the C++ standard library that provides additional functionality for your use. The C++ standard library is divided into areas (sometimes also called libraries, even though they’re just parts of the standard library), each of which focus on providing a specific type of functionality. One of the most commonly used parts of the C++ standard library is the iostream library, which contains functionality for writing to the screen and getting input from a console user.

Taking a look at a sample program

Now that you have a brief understanding of what statements, functions, and libraries are, let’s look at a simple “hello world” program:

Line 1 is a special type of statement called a preprocessor directive. Preprocessor directives tell the compiler to perform a special task. In this case, we are telling the compiler that we would like to add the contents of the iostream header to our program. The iostream header allows us to access functionality from the iostream library, which will allow us to write text to the screen.

Line 2 is blank, and is ignored by the compiler.

Line 3 declares the main() function, which as you learned above, is mandatory. Every program must have a main() function.

Lines 4 and 7 tell the compiler which lines are part of the main function. Everything between the opening curly brace on line 4 and the closing curly brace on line 7 is considered part of the main() function.

Line 5 is our first statement (you can tell it’s a statement because it ends with a semicolon), and it is an output 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.

(Remember, Visual Studio users should add #include “stdafx.h” as the first line of any C++ code file written in Visual Studio)

Syntax and syntax errors

In English, sentences are constructed according to specific grammatical rules that you probably learned in English class in school. For example, normal sentences end in a period. The rules that govern how sentences are constructed in a language is called syntax. If you forget the period and run two sentences together, this is a violation of the English language syntax.

C++ has a syntax too: rules about how your programs must be constructed in order to be considered valid. When you compile your program, the compiler is responsible for making sure your program follows the basic syntax of the C++ language. If you violate a rule, the compiler will complain when you try to compile your program, and issue you a syntax error.

For example, you learned above that statements must end in a semicolon.

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

Visual studio produces the following error:

c:\users\apomeranz\documents\visual studio 2013\projects\test1\test1\test1.cpp(6): error C2143: syntax error : missing ';' before 'return'

This is telling you that you have a syntax error on line 6: You’ve forgotten a semicolon before the return. In this case, the error is actually at the end of line 5. Often, the compiler will pinpoint the exact line where the syntax error occurs for you. However, sometimes it doesn’t notice until the next line.

Syntax errors are common when writing a program. Fortunately, they’re often easily fixable. The program can only be fully compiled (and executed) once all syntax errors are resolved.

Quiz

The following quiz is meant to reinforce your understanding of the material presented above.

1) What is the difference between a statement and an expression?
2) What is the difference between a function and a library?
3) What symbol are statements in C++ often ended with?
4) What is a syntax error?

Quiz Answers

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

1) Show Solution

2) Show Solution

3) Show Solution

4) Show Solution

1.2 -- Comments
Index
0.7 -- A few common C++ problems

217 comments to 1.1 — Structure of a program

  • 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

    hi
    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?
    Regards.
    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 fine..am 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";
            cin.get();
        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)

    Thanks

  • 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): ";
    cin>>antwort;

    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" >>
        system("PAUSE");
    }

    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 .

Leave a Comment

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