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

314 comments to 1.1 — Statements and the structure of a program

  • Akshit S

    So after execution of our program, compiler returns a value to the OS indicating whether or not our program was successfully compiled and executed. But, here we are already specifying a return value (in the above case, '0'). We forcefully want our compiler to tell our OS that there wasn't any error in our program. Shouldn't this job be handled by compiler itself, instead of user specifying a return value?

    • Alex

      At the end of execution of our program, the program returns a value to the OS (not the compiler).

      Typically, things happen in this order:
      * Programmer writes code.
      * Programmer uses compiler to compile code into an executable. (The compiler's job is done at this point)
      * User runs executable.
      * Executable returns a code to the OS to indicate whether the executable ran successfully.

      The compiler generally won't even be running when the executable is running (unless you're debugging).

  • Xola

    Hi how can I gt the minGw compiler, currently m using turbo C++
    It's quite tricky to work with.

  • Amir

    Hello.I am From Iran and in my University I Learned the Python very well. but dont teach the c++.
    this Site is very Special and very good.
    thanks for all your difficulty.

  • Sind

    int x;
    This tells the compiler that x is a variable

    Does this mean, memory is allocated for variable x when variable x is declared?
    What exactly is the difference between declaration and definition?

    • Alex

      Really good question about the difference between declaration and definition. The easiest way to think about it is as follows:

      * A declaration introduces an object object (function, variable, etc...) and it's type. A function prototype is an example of a declaration. A declaration is enough to satisfy the compiler. You can have multiple declarations for the same object.

      * A definition actually defines that object. A function with a body is an example of a definition. A definition is needed to satisfy the linker. There can only be one definition for an object.

      In many cases, a single line serves as both the declaration and definition. For example, "int x" is a declaration AND a definition.

      Memory is allocated at the point of instantiation, which is when the object (variable) is actually created. This point can vary depending on where the variable is. For example, if a variable lives inside a function, the variable won't be created (and memory assigned) until that function executes.

      • John Zulauf

        First, remember that the declaration is purely semantic. You have a name that logically associates with a type and a value.  What the compiler does will vary. See the section on build configurations above.  

        For "debug" builds, variables local to a function are typically given memory when first assigned a value.  That memory is only present for as long as the variable is in scope (i.e. code is executing within the {} the variable was defined in, and then is subject to reuse.

        For release builds, typically the compliers optimizer is enabled -- and all bets are off.  Local variables (those that are part of a function) are not guaranteed to have *any* memory is allocated. Depending on how x is used, x may only ever exist inside a CPU register and never be stored to memory.  Other optimizations might collapse all logical operations on x to a logically equivalent set of instructions that don't ever have any of the values that x would logically take on.

        Debugging release builds can be a serious pain, and bugs that only exist in release builds are among the most pernicious.

  • Maria

    very nice working...........

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

  • Ali 1

    Thanks for this site owner's

  • thanks for every one who do this site thanx much

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

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

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

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

    • Umair

      I think this one is more appropriate:

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

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

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

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

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

  • chris03653837

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

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

  • venne

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

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

  • Noha

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

  • The Leading Man

    ................................................ skew you

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

  • adam

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

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

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

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

Leave a Comment

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