Search

1.1 — Structure of a program

A computer program is a sequence of instructions that tell the computer what to do. Programs are typically composed of 3 basic elements: expressions, statements, and functions.

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, which we use 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 (but not always) terminated by a semicolon.

There are many different kinds of statements in C++. Here are a few example statements that you might find in a program:

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. All variables in a program must be declared before they are used. We will talk more about variables shortly.

x = 5; is a statement that assigns a value (5) to a variable (x) so we can use that value later (which we do, on the next line).

std::cout << x; is a statement that outputs the value of variable x (which we set to 5 in the previous statement) to the screen.

Expressions

The compiler is also capable of resolving expressions. Expressions specify a computation to be performed. For example, as children we all learn that 2 + 3 equals 5. In programming, we say that 2 + 3 is an expression that evaluates to the value 5.

Here are some examples of different types of expressions:

You’ll note that expressions can contain literal values (such as 2, which evaluates to 2, or “Hello, world” which represents text). Expression can also contain variables (such as x, which evaluates to whatever value variable x is holding), mathematical operators (such as +, which does addition), and function calls (not shown above, but to be discussed shortly).

For example, x = 5 (no semicolon on the end) is a valid expression that assigns the value of 5 to variable x.

Expressions can not be compiled by themselves, as they are meant to be used inside statements. For example, if you were to try compiling the expression x = 5, your compiler would complain (probably about a missing semicolon).

Fortunately, it’s extremely easy to convert an expression into an equivalent statement. An expression statement is a statement that consists of an expression followed by a semicolon. Thus, we can take an expression (such as x = 5), and turn it into an expression statement x = 5; that will compile.

It’s interesting to note that some statements may contain multiple expressions. We’ll see examples of these in future lessons.

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, expressions, 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 expression 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.

(Note: If you want to compile this program yourself, you can. Reminder to Visual Studio users, you will need to ensure precompiled headers are turned off, or else add #include “stdafx.h” (or #include “pch.h” if using the latest versions of Visual Studio 2017) to 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 many types of 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
A few common C++ problems

261 comments to 1.1 — Structure of a program

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

    • Alex

      Yes, and if you type "C++ operating system" into Google, you'll find open source versions of such operating systems that you can examine/modify/contribute to.

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