Introduction to C++

Read time: 37 minutes (9341 words)

See also

Text: Chapter 2

Obviously, when you develope programs in C++, you will spend most of your time writing statements that manipulate your data. We need to review the basic statements of this language, and see how they are different from those you learned in your previous language. We will use something called “syntax diagrams” to show you how things are put together.

Note

These diagrams are a common way to explain how oyu are to build programs. Following these diagrams will result in no syntax errors in your code! we will look at those syntax diagrams to see how they are put together. Trust me, the compiler will tell you if you write them wrong.

We will also peek at something called EBNF (Extended Backus-Naur Form), a formal notation used by compiler writers to accurately define what is legal in an programming language. This notation is commonly seem in many language documents, so looking at it will help you when you lern other languages, or try your hand at writing a compiler.

Note

These diagrams and EBNF rules say nothing about style.. We will spend some time on style in a later lecture. For now, we will concentrate on learning on how the statements are formed.

Basic structures

All modern programming languages are based on the three basic programming structures:

The sequence

../_images/Sequence.png

This structure is obvious. We perform one thing after another!

The decision

../_images/Decision.png

This structure forms the basic of making decisions in our programs. We form expressions that produce logical results. Those results have only true or false values` and will cause us to branch in one of only two possible ways in our programs. We can combine several sets of these to perform more complex questions, but they all boil down to basic two state questions.

The loop

../_images/WhileDo.png

This loop asks a question that decides whether to do a task or not. If we do the task, we go back and ask the question again. The minimum number of times we do the task is zero in this form of loop. Obviously, we could set up other forms of loops, but this one is probably the most general.

There are other forms of statements, added to our arsenal of programming tools just to make our lives as programmers more simple. They are not really essential. In the material that follows, I will show you syntax diagrams for the most common forms of C++ statements you will be using in this class. These are by no means the only C++ statements you will learn, just a set to get you started. You should start here, then study these and see if they map into Python, or other languages you might have seen before.

Introductory C++ Statements

Let’s see the most common statements you will need to learn:

Assignment Statement

../_images/Assignment.png

The identifier shown here names a variable in your program. You should pick a name that helps you understand what that variablle is all about. max_count is much better than x24!

C++ is very different from a language like Python in that all variables you use must be declared first. That declaration will tell the compiler what type of data this variable will hold. Typical types might be these:

  • int - signed integers
  • float - floating point numbers
  • char - single characters

There re lots of other types, and we will explore them later.

If Statement

../_images/if_statement.png

That condition is a logical expression where we ask a question about our data. You will typically form a logical expression using a relational operator. These should look familiar:

  • > - greater than
  • >= - greater than or equal
  • < - less than
  • <= - less than or equal
  • != - not equal
  • == - is equal to

Logical expressions always evaluate to a boolean value of true or false (note the case) in C++.

You can also use the not operator, which is the exclaimation point.

  • !(a >= b) - means a is less than b, right? (What is the opposite of greater than or equal?)

While Statement

../_images/while_statement.png

Notice we use another condition here. This one controls whether we loop or not. If you manage to get into the loop, you must alter something in the loop body to make the condition fail, or you will loop “forever” (or until you kill the program!)

Do-While Statement

../_images/do_statement.png

For Statement

../_images/for_statement.png

Compound Statement

../_images/compound_statement.png

Obviously, these are not complete, but they are enough to get you started. Your book has examples that will get you going. Use the example code in the book to fill in the missing details. In the next section, we will look at how you should structure a project.

Writing your Code

You will be writing a number of C++ programs in this class. So, let’s start off with a good foundation. Here is a template you should use as a start on every program you write. The template is not a single file, it is a directory structure with a number of things I will require that you include in each project you submit for grading!

Setting up a new project

As part of my effort to improve your programming professionalism, I am going to require a defined directory structure for all work you submit for grading. Here is how to set things up. This will be simple to do, I have created a project directory template on my GitHub account for you to download and use. Here is information to get you started:

Note

Be sure to read over the academic-integrity file, and note what it says. I am requiring that you include this file in each project. I take this seriously! In a normal project, this file would be replaced by one named LICENSE where you identify your ownership of this project, and any restrictions on the use of your code.

Program Starting Point

The sample program in this template will get you started, but it is not what I expect to see in your actual code. Every file you create should include a header at the top indicating who wrote the file, when, and why, and anything else that will make it easier for someone else to figure out why they are even reading this code. Here is a better starting point:

// hello.cpp - basic hello, world test program
//
// Author: Roie R. Black
// Date: Sept 2, 2018
// Course: COSC1337
//
// to compile, try this:
//      gcc hello.cpp -o hello.exe (leave off the .exe on Mac/Linux)
//
include <iostream>

int main(int argc, char ** argv) {
    cout << "Hello, World!" << endl;

    return 0;
}

Warning

That header very definitely should be changed on your submissions. If It looks like I wrote it, and grades will be given to me, not you!

Obviously, as we write programs with more than one file, the header at the top of each file should be different. The primary routines in each file should be mentioned in the header, as should basic information on how to use those routines.

EBNF Start Rule

Since I showed you the EBNF notation, let’s include a rule for your main routine in any C++ program:

These rules, while formally correct, do not say anything about style, and style is something you must learn how to use. Failure to consider style is a serious offense in the programming world, in spite of the fact that the language does not care (except for Python, of course). Use good style!

What are all of these things?

Includes

Includes are those lines that provide access to routines defined elsewhere. In our normal template we include this line:

#include <iostream>

The sharp character at the front of this line actually marks this line as a directive to something called the C++ Preprocessor, a tool that reads your file and prepares it for actual compiling. In this case, the contents of a file named iostream are located and copied into your file before your file is handed to the compiler. The angle brackets around the file name tell the preprocessor that this file is located where the compiler, itself, is located on your system. It is a system file. User files we want to include will be named with quotes, inside of which we will tell the system where the file is located.

Function Header

The function header defines something called a signature for this function. In C++ a signature for a function includes the return type (if any) of the function (int in this case, the name of the function (main) and the number and type of any arguments the function requires). Our main function has an integer return type, the name main, and exactly two arguments, the first an integer, and the second, well, it is a pointer to an array of strings. DOn’t worry about that for now, we will get to it.

Function Arguments

A function can have zero of more arguments (or parameters, as they are also called). The open and close parentheses are required in any case.

The arguments in this case is a comma-separated list of two items:

The actual names argc and argc can be anything you like, but folks will look at you funny if you change them.

Function Body

The function body is where all the action is. Those parameters have names, and those names are available inside the body. We can include as many statements as we like. The body is actually a rule you will see elsewhere in the language. A block of statements surrounded by curly braces is what is required here. That same block of statements will appear twice in an if-then-else statement as we will see later.

The very last of the statements in the main function body should be this:

return 0;

Which hands back the value zero to the operating system which is what will actually launch your program. Windows could care less about this value, but other operating systems pay attention to this. Scripts that launch a number of programs in a row will use the return code to decide if to continue or not. Any return value other than zero is considered a failure, and that will stop further processing in a script. This line is often left off, with no problems, but it is still good to include it.

The statement list in the body of your main function can be very complex, but that makes figuring out what you are doing just plain hard. I recommend that you use other procedures/functions to break up your code into logical parts with good names, so the reader can see the basic organization of your program easily. Here is something you might see:

int main(int argc, char ** argv) {
    get_input_data();
    process_data()
    output_final_results()

    return 0;
}

I have no problem with asking a program to identify itself, especially if it is a console program. Just replace “Hello, World” with something more meaningful!