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 “console 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

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

  • wonderful tutorial site! thank you.

  • Markus Carter

    i am reading a book called bjarne stroustrup principle and practice of c++ second edition. i wanted to do the question below:

    Write a program that “bleeps” out words that you don’t like; that is, you read in words using cin and print them again on cout. If a word is among a few you have defined, you write out BLEEP instead of that word. Start with one “disliked word” such as
    string disliked = “Broccoli”;
    When that works, add a few more.

    when i tried to compile my program i got 2 errors:
    - identifier "choose_words" is undefined
    - identifier "bleeped_word" is undefined

    it worked before i separated my code into two different functions. if anyone knows what is going on please help i am confused.

    here is my code:

    • Lesson 2.7 Forward declarations and definitions

    • MRRP

      Hi Markus, i had compiled the code in my PC and it appears you have the following errors:

      First: i think in the "choose_words" function, in the function declaration, the argument "word" must be "&words" because if you dont put that when you return from that function the vector "words" in the "main" function will stay empty;

      Second: You must move the statement from line 13 to between lines 15 and 16, if not, "bleeped_words" will be empty and in "bleep_word" an segment violation error will be produced when trying to access elements from that vector that doesnt exist. If you put it between lines 15 and 16, then "bleeped_words" will have the same number of elements than "words" (but without text) and it will work as intended.  

      Third: You must change the line "if (word == "exit") finish_input = true;" to "if (word == "exit") finish_bleeping = true;" if you dont do that the loop in the second function will never end.

      Fourth: change the line 72 and the for loop from line 74 to something like

      P.D.1: In my IDE i had writen first the 3 functions and the "main" function last of all.

    • Happy-vn

      Hi Markus
      I has compiled the code on my PC and I have solved  the same problem as you by adding prototype of tow function "choose_words" and "bleep_word" before function main() and the problem is solved
      If you see something more. Please, share it

  • Frank

    Hi,
    Completely novice to this subject; just wondering if a automatic trading strategy can be written for Ninja Trade 8 can be written/developed with this language. If yes, can you provide  example, how to do that? Thanks

  • nullptr

    The first paragraph under the expression examples

    "You’ll note that expressions can contain literal values ... and function calls (not shown above, but to be discussed shortly).", isn't std::cout << x an overloaded operator, which is a function call? I might be wrong about that one, just asking.

  • anonymous

    hi there..i am using Emulated Turbo C++ IDE 3.0 compiler and when I write #include<iostream>
    my compiler is showing error..why????and when I use #include<iostream.h> it is working in cpp ???pls help

    • Alex

      Because your compiler is seriously out of date and not compliant with modern C++ standards. Please download and install a modern compiler as suggested in the previous chapter.

  • Jeremy

    I don't understand how "Hello, world!" is an expression in conventional programming? It states in the solution "An expression is a mathematical entity that evaluates to a value. Expressions are often used inside of statements".

    Also i dont understand how x = 5 is an expression, i thought it was just assignment?

    Maybe someone can help me?

    • I'm not listing all the steps required to get to expression, because that's too many and I don't see it being useful.

      "Hello, world!"
      is a string-literal, which is a primary-expression.

      x
      is an identifier, which is a an id-expression, which is a primary-expression.

      5
      is a an integer-literal, which is a primary-expression.

      x = 5
      is an assignment-expression.

      Knowing the names of certain constructs is not necessary to understand the language (But definitely helpful). If you like this kind of stuff you can take a look at compiler development (You should know a programming language before you do that).

      • Jeremy

        Thanks for clearing that up. I would like to look at compiler developement so i can try to get a full understanding, but as you say, after i completely learn a programming language first. Thank you.

  • eocon

    not extremely important, but under expressions you put "Hello, world" instead of "Hello, world!".
    not important just the ! is needed.

  • der nerd

    "std::cout << x; is a statement that outputs the value of variable x [...] to the screen." this is wrong. std::cout outputs to stdout, which may be redirected.

    • Alex

      Not wrong so much as simplified. For console applications, std::cout outputs to the console, which appears on the screen by default.

      The fact that it goes through the stdout stream and can be redirected is not at all relevant to this lesson.

  • Excited Student

    Hey, Alex! Thanks so much for putting out these tutorials. I've wanted to be a programmer for so long, but have been unable to find any website to teach me to code until now. Thanks!

    I just wanted to let you know that there is an error with this, just at the very end, with the links to take you forward to the next lesson and back to the last one. The like to the last lesson will take us back to 0.8, instead of 0.10. I assume it's because lessons 0.9 and 0.10 are brand new.
    Just thought you would like to know this.

    Thanks again!

  • Alpesh Jamgade

    i know that Single quotes can only hold a single character, and double quotes can hold any amount of characters.
    but when i tried using single quotes for the string -hello world , in the hello world program , i got, in the result , some random numbers. i want to know what is happening here.
    why the compliler not showing any error , but some random numbers.

    • Make sure you enabled all compiler warnings as described in lesson 0.11. You should be getting warnings.
      When you write multiple characters in single quotes, that's an integer. But the value is implementation-defined, meaning that compiling your code with another compiler might produce different results.

    • Alex

      It is treated as a multibyte character, but the value is implementation-defined, which means you should generally avoid doing this at all.

  • Wulfred

    You say you can type instructions like

    but 'x' does not name type because you're not declaring it anywhere beforehand.

    • Ala

      int x() can be used as a function, just like main() used in the lesson:

      but if you want to use x as the variable instead of y, you can do it. You should change the name of the function, so that they won't be the same.

    • Ala

      I forgot to use return 0;
      Oh and I think we'll learn about names and such. Maybe there are functions that have similar names to their variables.

    • Alex

      The lesson has:

      You typed:

      The former is a definition of an integer variable named x. The latter is a forward declaration for a function named x that takes no parameters and returns an integer.

  • akon

    hi guys
    im a new learner of Computer programming and i need your tips and advises and etc.

    thanks for attention and your time

  • Prathvi

    in the previous code of hello world program , u used << std::end1; after "HelloWOrld!"
    but this time u omitted that part and still this works perfectly fine. Reason pls?

    • Hi Prathvi!

      std::endl adds a line feed to the output.

      prints

      prints

      If your program is using console output you should always print a line feed at the very end.

  • Big Thanks for all tutorials man.

  • kishore

    This is one of the best tutorial I have ever seen.. My hunt is over

  • Rahil

    Can I make an operating system
    with c++

  • Namenotneeded

    what is conio.h and std:: for thanks in advance.

    • nascardriver

      Hi!

      conio.h provides CONsole Input and Output functions in C, use <iostream> in C++.
      std::x means that you want to access x in the std namespace. A namespace is used to separate functions and variables from each other, "std" is short for "standard".

  • Namenotneeded

    Ive seen people using <iostream.h> and <conio.h>.why have you not used the .h thing

  • Josh

    I'm watching a Lynda course and the tutor uses "int main( int argc, char ** argv )" any reason why, not seen it in any other tutorials?

  • Josh

    I think that "statements must end in a semicolon" conflicts with "Statements in C++ are often (but not always) terminated by a semicolon." :)

  • Josh

    Is it possible to put the reference link "http://stackoverflow.com/questions/11043340/what-kind-of-statements-dont-require-semicolon-termination-in-c" for "Statements in C++ are often (but not always) terminated by a semicolon." I think that may be easier for other people to find the answer and don't have to check out the comment. :)

    • Alex

      I'm torn on this one. One one hand, it's interesting for those who like a lot of detail. On the other hand, we haven't defined any of these types of statements yet, so at this point in the tutorial this seem more like trivia than anything of value...

  • Bob Bob

    HI, I am just looking through the sample program provided at the top of the page and have been wondering the following questions

    (1) Why is there a space between the pre-processor  directives and the int main function. Is there some sort of advantage gained from this practice(from a technical standpoint)
    Or a specific reason why it is less left blank ?
    Included in the sample program(1.1)

    (2) Does the language of C++ change direction ( for example some languages do read right of the page to the left side of the page. Would this occur in Line 5 ( of the sample program), thereby syntax order  changing
    Hence
    Hello World would first be read and then sent to the std::cout variable

    A follow up question from this  would be : Is there some of processing order that a compiler(this may be incorrect) follows (once a person writes a program  that fits the rules of the language)  

    Sample Code :
    #include "stdafx.h" // Line 1
    #include <iostream> // Line 2
    -- Blank----        // Line 3
    int main()          // Line 4
    {
    std::cout << "Hello world !"; // Line 5
       return 0;        // Line 6
    }                   // Line 7

    • nascardriver

      Hi Bob!

      1. Readability. C++ doesn't care about whitespace.
      2. This is too much for a reply, you're best off reading through the tutorials and learn execution order step by step. C++ is usually read left-to-right.
      There is a standard for C++ which compiler developers have to follow. The compilation process itself is entirely up to them though.

  • kamal

    Hi, I am using Eclipse IDE to run C++ code, however I observe that even a simple piece of code takes 6-7 seconds to compile and run. Feels like a long time ... Please help me to reduce run time since code will only increase in complexity... Cant find anything on google, some website said that Eclipse does not support pre-compiled headers (not sure if accurate)

    Sample code:
    #include <iostream>
    int main()
    {
        using namespace std;
        int x=12334;
        int y;
        cout << x << "\n";
        cout << (y=30);
        return 0;
    }

  • Neil

    Hi Alex

    I thought I was doing well and keeping up with the subject matter, then this happened:

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

    Sorry that one went totally over my head. I have a sneaky suspicion that I am missing something so obvious here and making it unnecessarily complicated.

    Are you saying that you simply rename the main() for whatever your project is called? Thus, HelloWorld()?

    • nascardriver

      Hi Neil!

      No, the main function must be called main and look like one of the following

      Everything else is invalid.

      • Neil

        Thank you for your reply. I thought as much, but was confused as to what he was saying as my program was already called HelloWorld.cpp, anyway.

        • nascardriver

          You can name your files however you want, but it's convention to name the file which contains the main function either main.cpp or YourProjectName.cpp. So, if your project is called HelloWorld everything is fine.

        • Alex

          Is there something I could have said that would have made this more clear on first read?

  • Pork and Beans

    Hello.

    I hesitate to ask questions here.  I do not want to clutter up this section.

    I have been creating simple C++ programs using the tools that have been presented to us up to chapter 1.4.  I am using Visual Studio 2017.  Each time I create a new program, I find myself opening a new project.  I would like to know a better way to organize my scripts so that I can have one project for each chapter and be able to store my separate scripts within projects that correspond with each chapter.  I know that there must be a way to store multiple scripts within each project but I notice that when I try to do so, I get compile errors.  I can take the same script that gets compile errors, open a new project, copy the script into a new project and it will compile successfully.  What am I missing here?

    Thanks for your time.

    • nascardriver

      Hi Pork and Beans!

      > scripts
      C++ isn't a script language, there is source code, header files and source files but no scripts.

      > What am I missing here?
      Each project may have only 1 main function, that's why your compiler is complaining.

      Once multiple files, header guards and namespaces have been covered you can create a folder (Or filter in VS) in your project for each lesson and call the relevant functions from main.
      Until then you can write a custom main for each lesson and call those from main, this will clutter up your main.cpp though.

    • Alex

      A project can only have a single program. However, in visual studio, you can put multiple projects inside a solution. This is still a lot of overhead, as you still have to create a new project for each program you want to save.

      Nascardriver's suggestion is a reasonable compromise when learning.

      • Pork and Beans

        Hello Alex (and NascarDriver),

        I hope this message finds you well.

        Thank you for your replies to my message.  I will admit, I took a sojourn in utter confusion.  Then, I had prepared a message full of further questions for you (or anyone willing to read it).  Then I discarded that message - I will always try to solve the problem before asking you here, as I don't want to seem like I'm taking advantage of anyone here.

        That being said, I am very happy to know that I can still post questions here as a last resort.

        I am also pleased to share with you that (thank you, NascarDriver) NascarDriver's advice worked with terrific results.  Upon successful implementation of this method, I was better able to understand how functions (and the "void" declaration) work.  Now I am able to organize my code (I had to erase the word "script" here (what is the difference? I'd sincerely like to know)) into great and explanatory projects as I advance through this material.

        I truly appreciate this source of knowledge as I once again take up the banner and forge onward.

        Please stay in contact and thank you again.  Have a good evening.

        • nascardriver

          I'm glad to hear you found a fitting solution.

          > what is the difference?
          A script gets interpreted (Another program reads the script and executes it) whereas C++ gets compiled (You get a binary).

          Feel free to ask whatever questions you have. Chances are good that if you have a certain question, someone else does too.

Leave a Comment

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