Search

1.1 — Statements and the structure of a program

Chapter introduction

Welcome to the first primary chapter of these C++ tutorials!

In this chapter, we’ll take a first look at a number of topics that are essential to every C++ program. Because there are quite a few topics to cover, we’ll cover most at a fairly shallow level (just enough to get by). The goal of this chapter is to help you understand how basic C++ programs are constructed. By the end of the chapter, you will be able to write your own simple programs.

In future chapters, we’ll revisit the majority of these topics and explore them in more detail. We’ll also introduce new concepts that build on top of these.

In order to keep the lesson lengths manageable, topics may be split over several subsequent lessons. If you feel like some important concept isn’t covered in a lesson, it’s possible it’s covered in the next lesson.

Statements

A computer program is a sequence of instructions that tell the computer what to do. A statement is a type of instruction that causes the program to perform some action.

Statements are by far the most common type of instruction in a C++ program. This is because they are the smallest independent unit of computation in the C++ language. In that regard, they act much like sentences do in natural language. When we want to convey an idea to another person, we typically write or speak in sentences (not in random words or syllables). In C++, when we want to have our program do something, we typically write statements.

Most (but not all) statements in C++ end in a semicolon. If you see a line that ends in a semicolon, it’s probably a statement.

In a high-level language such as C++, a single statement may compile into many machine language instructions.

For advanced readers

There are many different kinds of statements in C++:

  1. Declaration statements
  2. Jump statements
  3. Expression statements
  4. Compound statements
  5. Selection statements (conditionals)
  6. Iteration statements (loops)
  7. Try blocks

By the time you’re through with this tutorial series, you’ll understand what all of these are!

Functions and the main function

In C++, statements are typically grouped into units called functions. A function is a collection of statements that executes sequentially. As you learn to write your own programs, you’ll be able to create your own functions and mix and match statements in any way you please (we’ll show how in a future lesson).

Rule

Every C++ program must have a special function named main (all lower case letters). When the program is run, execution starts with the first statement inside of function main and then continues sequentially.

Programs typically terminate (finish running) when the last statement inside function main is executed (though they may abort early in some circumstances).

Functions are typically written to do a 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 from a set of test scores. We will talk a lot more about functions soon, as they are the most commonly used organizing tool in a program.

Author's note

When discussing functions, it’s fairly common shorthand to append a pair of parenthesis to the end of the function’s name. For example, if you see the term main() or doSomething(), this is shorthand for functions named main or doSomething respectively. This helps differentiate functions from other kinds of objects (such as variables) without having to write the word “function” each time.

Dissecting Hello world!

Now that you have a brief understanding of what statements and functions are, let’s return to our “Hello world” program and take a high-level look at what each line does in more detail.

Line 1 is a special type of line called a preprocessor directive. This preprocessor directive indicates that we would like to use the contents of the iostream library, which is the part of the C++ standard library that allows us to read and write text from/to the console. We need this line in order to use std::cout on line 5. Excluding this line would result in a compile error on line 5, as the compiler wouldn’t otherwise know what std::cout is.

Line 2 is blank, and is ignored by the compiler. This line exists only to help make the program more readable to humans (by separating the #include preprocessor directive and the subsequent parts of the program).

Line 3 tells the compiler that we’re going to write (define) a function called main. As you learned above, every C++ program must have a main function or it will fail to compile.

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. This is called the function body.

Line 5 is the first statement within function main, and is the first statement that will execute when we run our program. std::cout (which stands for “character output”) and the operator << allow us to send letters or numbers to the console to be output. In this case, we’re sending it the text “Hello world!”, which will be output to the console. This statement creates the visible output of the program.

Line 6 is a return statement. When an executable program finishes running, the program sends a value back to the operating system in order to indicate whether it ran successfully or not. This particular return statement returns the value of 0 to the operating system, which means “everything went okay!”. This is the last statement in the program that executes.

All of the programs we write will follow this general template, or a variation on it.

Author's note

If parts (or all) of the above explanation are confusing, that’s to be expected at this point. This was just to provide a quick overview. Subsequent lessons will dig into all of the above topics, with plenty of additional explanation and examples.

You can compile and run this program yourself, and you will see that it outputs the following to the console:

Hello world!

If you run into issues compiling or executing this program, check out lesson 0.8 -- A few common C++ problems.

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.

Let’s see what happens if we omit the semicolon on line 5 of the “Hello world” program, like this:

Feel free to compile this ill-formed program yourself.

Visual Studio produces the following error (your compiler may generate an error message with different wording):

c:\vcprojects\test1.cpp(6): error C2143: syntax error : missing ';' before 'return'

This is telling you that you have a syntax error on line 6: the compiler was expecting a semicolon before the return statement, but it didn’t find one. Although the compiler will tell you which line of code it was compiling when it encountered the syntax error, the omission may actually be on a previous line. In this case, the error is actually at the end of line 5 (the compiler didn’t discover the issue until line 6).

Syntax errors are common when writing a program. Fortunately, they’re typically straightforward to find and fix, as the compiler will generally point you right at them. Compilation of a program will only complete once all syntax errors are resolved.

You can try deleting characters or even whole lines from the “Hello world” program to see different kinds of errors that get generated. Try restoring the missing semicolon at the end of line 5, and then deleting lines 1, 3, or 4 and see what happens.

Quiz time

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

Question #1

What is a statement?

Show Solution

Question #2

What is a function?

Show Solution

Question #3

What is the name of the function that all program must have?

Show Solution

Question #4

When a program is run, where does execution start?

Show Solution

Question #5

What symbol are statements in C++ often ended with?

Show Solution

Question #6

What is a syntax error?

Show Solution

Question #7

What is the C++ Standard Library?

Show Hint

Show Solution


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

306 comments to 1.1 — Statements and the 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 all code inside code tags: [code]your code here[/code]