2. First Programs

A First Program

Any C++ program we write will be composed of a sequence of statements, like the ones we have just written, enclosed inside a piece of magic called the function 'main'.

For example, to make a program out of the statement

5 + 3.14;

we would have to write the following:

The word int denotes the return type of function main. Types will be discussed in a later chapter.

int main()
{
    5 + 3.14;
}

By doing this, the statement '5 + 3.14;' has been made a part of a so-called function 'main'. This function makes up the main (and in this case, only) part of our program.

To execute this statement, we must execute the expression it contains. An expression is executed by evaluation, simple as that. In this case, the expression 5 + 3.14 evaluates to the number 8.14.

However, what is the meaning of a semicolon symbol? In addition to being a way to terminate expressions and mark the end of a statement, it instructs the reader or the executor of the program to discard the value of the expression preceding it.

This may strike you as bizarre. Why would one make the effort to obtain the result of adding 5 to 3.14 only to throw it away?

Think of it this way. Say you tell your friends: "Calculate what 5+3.14 evaluates to!" in a rather imperative voice. Normally, you would expect them to respond with the result, "8.14". However, should they not have understood your unstated request, you could clarify by saying: "Now tell me the result!" Having done that, you would have explicitly stated your true request, leaving no room for confusion.

In computer programming, we do not have that luxury. If we are to be understood at all, we must make the extra effort, and state explicitly and upfront that we want to know the result of a computation. Since we have not done that, the result of computing the expression 5 + 3.14 will be discarded and the whole effort rendered useless.