C++ tutorial: comments


Statements tell the computer what to do
As far as the computer is concerned, the program consists of a number of statments. A statement is an instruction to do something. Some statements will correspond to simple actions in the computer, like adding two numbers together, while some will produce very complicated actions. Statements have a semicolon (;) at the end, to indicate to the compiler that this is the end of the statement. The compiler will be very fussy about semicolons, and many beginners find it hard to remember where they go. Practise will sort this out.

Comments tell people what the computer is to do
Because the language statements are so terse, it is customary to add comments to the program for the benefit of human readers. The comments will be ignored by the compiler, and therefore will not be part of the final program that the computer executes. Comments can be as long or short as you like. In my opinion, the program itself is not the place for extensive description; there is a place for this, in the design documentation. However, this is largely a matter of taste. At the very least, I would recommend a brief comment at the start of the program file saying what it is for and who wrote it.

A simple program: 'welcome.cpp'
Click here to look at this very simple program. When you have examined it, use your Web browser's 'back' function to get back to here.

'welcome.cpp' when executed simply displays the following message:

Welcome to BIS4221:
software engineering and management.

The first part of the program is a comment block saying what the program does, who wrote it, and when.

/*==============================================================================

     Program: Welcome

     File: welcome.cpp

     Author: Kevin Boone

     Purpose: 1. to display a simple message
              2. to demonstrate the structure of a simple C program
              3. to give students practise in downloading and compiling files

     History:
     Created 5/12/97

================================================================================*/

This part is not meaningful to the computer, it simply tells the reader what's going on. The fact that this is a comment is signalled by the use of the symbols '/*' (start of comment) and '*/' (end of comment).

Another way of introducing a comment is the symbol '//'. This means 'the rest of the line is a comment'. You can put anything you like after '//' and the computer will ignore it.

Everything else in the program is a statement, that is, an instruction to do something.

©1994-2003 Kevin Boone, all rights reserved