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

  • 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

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

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

  • 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

  • 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 C++ code inside [code][/code] tags to use the syntax highlighter