Search

1.1 — Structure of a program


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

Statements and expressions

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 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. It tells the compiler that x is a variable. You may remember variables from math in school. They serve the same purpose here: to represent an arbitrary value. 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.

The compiler is also capable of resolving expressions. An expression is an 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 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.

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. One of the most commonly used libraries is the iostream library, which contains functions 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 use the iostream library. The iostream library will allow us to write to the screen.

Line 2 has nothing on it, 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) called the output operator. std::cout understands that anything sent to it via the output operator should be printed on the screen.

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.

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 do statements in C++ end with?

Quiz Answers

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

1) Show Solution

2) Show Solution

3) Show Solution

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

44 comments to 1.1 — Structure of a program

  • Thanks for this part of the tutorial. I found this section really helpful.

  • parasyte

    hey man very nice though you wrote ” would like to use the iosteam library.” in the first paragraph after
    “Taking a look at a sample program”

    • I’m not sure what the problem is with that. Am I missing something? :)

      • sorry188

        iosteam should be iostream. It is missing an “r”.

        [ Wow, I can’t believe I didn’t see that. Fixed now! Thanks all. -Alex ]

      • ghost

        using namespace std; is in the wrong line
        it should be in the main header before int main( )

        • Alex

          No, it shouldn’t. If it’s in the main function, the scope of the statement only applies to the function (which is good). If you put it in the main part of the program, it applies to the entire file, which is generally considered poor form (and could lead to naming collisions).

      • Gilbert

        I’m not sure if it differentiates between C++ Compilers or not but I’m using Visual C++ and my program will not compile unless the using namespace std; is outside of the main function

  • adam

    is an expression a type of statement?

    • I’m not quite sure how to answer that.

      In most cases, and expression is PART of a statement. For example:

      “2 + 3″ is an expression that evaluates to 5. x = 2 + 3 is an assignment statement that assigns the result of evaluation 2 + 3 to variable x.

      It is possible to have a statement that consists only of an expression. For example, the following is allowed:

      This expression evaluates to 5, but since the result is not used anywhere it is just discarded.

  • adam

    if “cout < < “Hello world!” << endl;” is a statement and “<<” is an operator what is “cout” a command?

    • cout is actually a variable that is predefined by the standard library. The variable is of type ostream, which is a class. Classes allow you to define your own variable types. We cover classes in more detail in chapter 8.

      • vivek

        if “cout” is an object of a class, then who actually does instantiate it ? we do not create this instance in our code. Is this object created before the actual code is executed ?

  • I have Visual C++ 2005 Express Edition,
    but my lines aren’t numbered. Why?

  • The Leading Man

    ………………………………………… skew you

  • Noha

    Is there any explanation about the structure of Standard Template Library (STL)in this site?

  • Ray

    Wow ur teaching or tutorial here is much better than my teacher. I’m currently studying engineering with c++ as a module but till now i nvr knew the true meaning of 0 at the return 0.

  • vishvesh

    It would be good if you could explain the difference between functions and methods.

    • Alex

      A method and a function are essentially the same thing. In C++, we usually use the term function when the function is independent of an object, and method (or more commonly, member function) when the function is part of an object/class.

  • venne

  • IsNe

    When i code i place the:

    at the top

    it still works, isn’t that more convinient? or is there a reason for placing it inside each and every function

    • Alex

      It’s more convenient perhaps, but also more dangerous. If you put the using namespace std; statement at the top of your code, it applies to everything in the file. This increases the chance of naming collisions.

      Generally, it’s better to either put the using statement in each function that needs it, or call cout directly using the scope resolution operator (e.g. std::cout).

  • chris03653837

    you gys need to stop smoking bad weed, the code is fine.

  • Met

    very good website this. thanks to the Admin of this website and the people who made this possiable to us. Great lessons

    thanks again

    Albanian.

  • Plz explain using namesapace std; in more understandable manner alex sir.

    • Adam Sinclair

      using namespace std; is basically using "std" throughout the entire code.

      Instead of writing std::cout:: << "Hello World!" << std::endl; or something like that. You won't have to include all that "std::" if you have

      using namespace std;

  • cubbi

    Endl is a special symbol that moves the cursor to the next line
    This is incorrect. The special symbol that moves the cursor to the next line is ‘\n’. Abuse of std::endl for this purpose is bad practice which leads to inefficient programs.

    • Alex

      I updated the wording to be more precise:

      Endl is another special object that, when used in conjunction with cout, causes the cursor to move to the next line (and ensures that anything that precedes it is printed on the screen immediately).

      You are correct that overuse of std::endl can cause performance issues in cases where flushing the buffer has a performance cost, such as when writing to disk. I made notes of this in lesson 13.6 — Basic File I/O, where I talk about buffering and flushing in more detail.

  • Homesweetrichard

    On mac (xcode) there will be one error if you follow it exactly as shown on this page. Instead use this one

    #include

    int main () {
    using namespace std;
    cout << "Hello world!" << endl;
    return 0;

    }

    Even if you have ignore white space on it will still err. So do not give "{" its own line thats bad programming on xcode. it took me a week to figure that out, because i was wondering why it wasnt "build & run" so i started to play around with spacing, after i had already asked 10 different sites why didnt this code work, turns out it does, just requires a certain spacing requirement. My guess is you cant use "{}" without telling it why its there. thats probably a bad explaination or wrong explaination.

  • ohhh… every nice i understand!
    thanks! learncpp.com

  • betefeel

    I started doing some things on my own hehehe

    #include

    int main()
    {

    int x;
    int y;
    int d;
    int f;
    x = 5;
    y = 5;
    d = x + y;
    f = d + d;

    using namespace std;
    cout << x + y << endl;
    cout << f << endl;
    return 0;

  • pmc24

    Consistency issue.

    For beginners, the move from

    using namespace std;

    to

    std::

    might be confusing.

    Hence I suggest amending the example code accordingly, or leaving a note at the end of the tutorial highlighting the interchangeability feature of the two.

  • ballooneh

    Hey there!

    I am wondering what “int” does in “int main()”.
    What does it do and when do i use it?

    I also read somewhere that you can use “void” instead of “int”.
    What does “void” mean and what does it do?

  • plus minus

    Why we need operators?

    • Alex

      Operators provide a convenient and concise way for us to get different things to interact.

      Take for example “3 + 4″. The + operator adds 3 and 4 to produce the result 7.

      With cout << “Hello world”, the << operator takes “Hello world” and gives it to cout to print on the screen. Without the << operator, the compiler wouldn’t know whether “Hello world” was meant to interact with cout or something else.

  • thanks for every one who do this site thanx much

  • Ali 1

    Thanks for this site owner’s

  • Joseph H

    I just started with the tutorial yesterday and completed my first program! I am in HS and want to learn c++ because I want to be a computer programmer! Thank you this is all good and if you have any tips for me or other codes I can learn online please comment!!! :)

Leave a Comment (Note: put C++ code inside [code][/code] brackets)

  

  

  

12 − eleven =

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">