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

  • 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

    Hello
    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

    Hey,
    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.

    http://www.heypasteit.com/clip/28UL

    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 🙂

    Regards,
    Pankaj

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

Leave a Comment

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