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

  • Pork and Beans

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

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

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

    Have an excellent day.

    • nascardriver

      Hi Pork and Beans!

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

      • Pork and Beans

        Thank you, Nascar Driver!

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

        I appreciate your input.  :-)

    • Alex

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

      • Pork and Beans

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

        Have an excellent evening.  Your work is greatly appreciated.

  • Zach

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

  • Sahil

    Hi Alex,

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

    Thanks.

  • J

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

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

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

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

    • Alex

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

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

  • Robert

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

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

    Regards

    Thanks for these tutorials!

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

  • Dan the African

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

    Overall good lesson, learnt a lot

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

    • ashutosh

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

      • Maxixxx

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

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

        • nascardriver

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

    • Alex

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

    • Porkinns

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

                     (or)  

                     (or)  

      (or)

    • sonia

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

      • Alex

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

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

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

  • Frank

    Great tutorial thank you very much!

  • syad abdul

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

  • Umair

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

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

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

    • Alex

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

  • Person 1

    Why you no use..

    using namespace std;

    • Alex

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

  • LTC

    I made a realy cool program that crashed my IDE

  • Max

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

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

    code:

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

    int main()
    {

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

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

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

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

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

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

            

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

        return 0;
    }

    • Alex

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

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

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

      • Prince

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

        • Alex

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

        • prince

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

  • Thomas

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

  • DanielLearnCPP

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

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

  • Gurdeep Singh

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

    • Alex

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

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

    • HarsshChaudhry

      its completely correct you can use it without no problem

      • SirElismyer

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

  • Sieun

    Alex, you are an awsome teacher

    • Alex

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

  • Michael

    Alex,

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

  • Karlosmi

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

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

    • Alex

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

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

  • Zuhayer

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

    How do I fix this? ;-;

    • Alex

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

  • Abheet

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

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

    • Alex

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

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

  • cool_boy

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

  • john

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

    • Alex

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

  • seth

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

  • DIKSHA

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

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

Leave a Comment

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