Learn Computing from the Experts | The Rheinwerk Computing Blog

What Are the Individual Program Elements of C++?

Written by Rheinwerk Computing | Dec 2, 2024 1:52:32 PM

In this blog post, we’ll briefly explain the individual program elements of C++ so that you have the basic knowledge necessary to start coding with the language.

 

Let’s consider this simple C++ program.

 

// https://godbolt.org/z/Mdj7bGvar

#include <iostream>                      // Include modules/libraries

int main()                               // main() is the start of the program

{

   int value = 100;                      // Variable with initial value

   std::cout << "Divisors of " << value << " are:\n";       // Output of text

   for(int divider=1; divider <= value; divider = divider+1 // loop from 1 to 100

   {                                                                      // begin of the repetition part

       if(value % divider == 0)          // test for conditional execution

           std::cout << divider << ", "; // only if the test is positive

 }                                       // end of the loop

   std::cout << "\n";                    // single output

   return 0;                             // means end of program in main()

}                                        // end of main()

 

Comments

As you can see, there is mixed program text and explanatory words here. The lines always start with program text, sometimes followed by a double slash //, and then come the explanatory words—the comment. In C++, you can write any text after //; the compiler ignores it (or, to be precise, interprets it similarly to a space) with a few exceptions. This allows you to tell other programmers, yourself, or posterity your intentions that led to the current program line.

 

The “include” Directive

The very first line of the example reads:

 

#include <iostream>

 

Use #include to inform the compiler that you want to use elements of a module in this file. The name between the brackets is the name of a header file containing the declarations of that module.

 

The Standard Library

We included the special module iostream because it contains std::cout. The program needs cout to generate the screen output. The iostream module is part of the standard library and is supplied with the compiler.

 

All names of the standard library begin with std, followed by the scope resolution operator ::. This is an ugly, albeit precise term that nobody uses; the name double colon is fine too.

 

The “main()” Function

Now let's look at the line that says main:

 

int main()

 

This defines a function with a special name. The main function is always the entry point into a C++ program: you can't do without it, and there can never be two. When your system executes the program, main() is called.

 

Otherwise, a function in C++ allows you to jump to this function from another location in the program and return to the call location later. Functions can take arguments—these are the function parameters—and return a result.

 

You can read the definition of this main function as follows:

  • main should return a number—a value of type int, to be precise.
  • The name of the function is main.
  • The empty pair of round brackets in main() means that the function does not receive any parameters.
  • This is followed by what the function actually does. This function body is always placed between two curly brackets {...}.

Functions other than main could return any other types.

 

The value returned by main is determined by the first return that the computer encounters when running the program. Here, this will always be return 0. The return value is therefore always 0.

 

Depending on the operating system, the return value can be evaluated. If your program is to be able to receive arguments on the command line, the round brackets for the parameters would not be empty.

 

Types

In C++, almost everything has a type, such as variables and intermediate results. The type determines which properties the construct has and which values it can accept.

 

Only int is specifically mentioned as a type. The compiler will work out everything else itself. Two variables with this type are introduced in the program: int value and int divisor. Whenever you refer to these variables in the course of your program, you must take their type int into account. There are exact properties of int but for now, it is sufficient to know that int stands for an integer.

 

Variables

A variable is the name for a memory area that can hold a value. Yes, in C++ a variable must always have a type. When you use a variable for the first time, you must tell the compiler its type. The type accompanies the variable as long as it lives and can no longer be changed.

 

In the program there are two variables: value represents the number whose divisor we output, and divisor is the number with which we check whether a division can be performed without remainder. First I define value. From this point on, you can use value, which is also done immediately for the output:

 

int value = 100;                                  // Variable with initial value

std::cout << "Divider of " << value << " are:\n"; // Output of text

 

Because value is of type int, you can only use this variable for integers—that is, use it in calculations or change it.

 

The other variable is divider in the for loop:

 

for(int divider = 1; divider <= value; divider = divider+1) // Loop from 1 to 100

 

The same applies to it as to value. Apart from the name, there are two other differences:

  • divisor is actually changed in the program sequence. If divider = ..., then it is assigned a new number.
  • divisor is only known within for.

The scope of a variable is limited to its block, after which it is literally gone. And so gone that you could define a new variable divider outside the for. This could then also have a completely different type.

 

Initialization

In the example program, the equal sign = fulfills two purposes that are often mixed up. However, because the distinction is so important, it’s important to be aware of this at an early stage.

 

You can see the equals signs in the following example:

 

int value = 100;

int divider = 1;

divider = divider+1;

 

The first two lines are each the initialization of a variable defined in the same breath. This point in time, at which you also define its type, is its declaration. You can only initialize something during the declaration.

 

The variable is already declared in the last line. You are therefore assigning a new value to an existing variable; this is why we speak of an assignment. With an assignment, you cannot change the type of the variable. If the types are different, the compiler can perform a conversion within certain limits.

 

Assignment versus Initialization: The equals sign in the declaration is always an initialization. It is only an assignment if the variable was declared somewhere else.

 

Output on the Console

With #include <iostream>, you've imported the part of the standard library that's responsible for input and output. The output to the console is done using the operator <<:

 

std::cout << divider << ", ";

 

On the left, you can see the variable originating from <iostream> with std::cout, which stands for the output on the console. To the right of each << are the things you want to output. As you can see, you can concatenate << like a normal plus + and thus output several things one after the other.

 

Some output is difficult to write in source code. C++ provides special mechanisms for this. One possibility is to escape certain characters with a backslash \ (slash reversed). If you want to output a line feed, write "\n" in the source code, for example.

 

Statements

The curly brackets {...} of main() hold together a group of statements together, and they define a statement block. They form the boundary of what is executed for main():

 

int main()

{

...

}

 

In between are statements that are executed one after the other. Statements are important basic elements in C++, and there are different types. Recognizing what a statement is and what type it is will quickly get you started with C++. In the next sections, you will get to know them all. At this point, we’ll show you which statements you can use. You will find the following in the sample program:

  • The declaration int value = 100; makes the variable value known and initializes it with an initial value—sometimes collectively called the initialization statement.
  • With cout << "divisor of " << value << " are:\n";, it is an expression that outputs something to the console.
  • This is followed by a for loop. It is used to execute other statements repeatedly. Note that the part that is to be repeated is again enclosed in curly braces {...} after the for.
  • This is because the two braces that belong to the for are, with their content, a compound statement or a statement block. This again contains a series of statements that are held together by the enclosing braces. This grouping of statements has a special meaning in several respects. On the one hand, they can be repeated together in the for loop, and on the other hand, this grouping forms a scope of validity for the variables it contains.
  • if(value % divider == 0)... is an if statement, a branching A condition is tested and the following statement std::cout << divider << ", "; is only executed if this condition is true. As with the for loop in the example, we could have followed this with a statement block in {...} (that would have been good style). For demonstration purposes, the if is only followed by a single statement. This way we could save the surrounding {...} for a statement block.
  • The return statement return 0; concludes this enumeration.

Statements are made up of expressions. An expression can have a value as a result at runtime. At compile time, the compiler knows the type of each expression. Here are just a few examples from the program:

  • value % divisor calculates the modulo—that is, the remainder of a division.
  • ... == 0 checks the equality of two values.
  • divisor+1 is the result of an addition.
  • divisor = ..., an assignment, is also an expression.

Editor’s note: This post has been adapted from a section of the book C++: The Comprehensive Guide by Torsten T. Will.