Resources

The component parts of a C++ source file

Aims

To enable students to:

  1. describe source, object and executable code

  2. create source code

  3. understand library files

  4. produce an executable program

Understand the structure of a C++ source file

Sample Program Notes

Describe the purpose of this source file.


/****************************************************/
/* */
/* Module name: sample.cpp */
/* */
/* Description: Writes 'Hello World' to the screen. */
/* */
/* Date: 10/10/1998 */
/* */
/* Change History: */
/* */
/* 10/10/1998 Module creation by RF */
/* */
/****************************************************/

Reference any header files required by this source file - in this case iostream.h as we use cout.

/****************************************************/	 
/* Header files */
/****************************************************/
#include <iostream.h>

Constants used in this source file - in this case there are none.

/****************************************************/	 
/* Constant definitions */
/****************************************************/
/* -- none -- */

Functions declared within this source file, in this case none other than the special function main.

/****************************************************/	
/* Function prototypes */
/****************************************************/
/* -- none -- */

Describes the purpose of the function.

/****************************************************/	 
/* */
/* Function name: main */
/* */
/* Description: Main function of the program. */
/* */
/* Parameters: none */
/* */
/* Returns: none */
/* */
/* Change History: */
/* */
/* 10/10/1998 Function creation by RF */
/* */
/****************************************************/
void main ()
{
cout << "Hello World\n";
}
  1. #include provides access to library routines

  2. all programs must have a function main ()

  3. ; terminates statements

  4. cout sends output to the screen

  5. "" indicates a string literal

  6. \n prints a newline

  7. C++ is case sensitive

  8. { } marks the beginning and end of program blocks (functions, loops, etc.)

Operate the preprocessor

Before converting source to object code the compiler will execute the preprocessor. The preprocessor performs preliminary operations on C++ files before they are passed to the compiler. The preprocessor allows you to:

  1. Define and undefine macros.

  2. Expand macros.

  3. Conditionally compile code (i.e. direct the actions of the compiler during compilation).

  4. Insert specified files.

  5. Specify compile-time error messages.

  6. Apply machine-specific rules to specified sections of code.

Instructions to the preprocessor are proceeded by a #, e.g. #include

The #include directive tells the preprocessor to treat the contents of a specified file as if those contents had appeared in the source program at the point where the directive appears. Usually this is used to reference the header files of libraries, for example iostream.h, which consist of a series of prototypes, one for each function supported by the library. By including the header file the compiler will recognise the functions called later within the source file, checking that they are being used correctly. To indicate to the preprocessor where the filename starts and ends < > are employed, with < marking the start and > the end, for example #include <iostream.h>.

The #define directive permits meaningful names to be assigned to constants in your program. For example, the statements #define RED 2 and #define BLUE 3 permit the programmer to use the terms RED and BLUE freely throughout the source code wherever the values 2 or 3 are expected. When the preprocessor parses the source file all occurrences of the name are replaced with their value (i.e. all instances of RED become 2).

Declare variables of an appropriate data type

There are two fundamental data types in C++, real for numeric values with decimal parts and integral for whole numbers and characters.

Examples of reals include, float and double, with the type determining the number of bytes used to hold the variable and thus the precision and range of values the variable can hold. The actual number of bytes used depends on the computer system. Values used in complicated calculations that must be exact to several decimal places, such as 12.4736, are stored in variables of type float. Note, it is entirely possible to store whole numbers, such as 12.0, in floats. A float declaration would appear as:

float fNumbmer; 

Integrals include int, char, and long again with the type determining the number of bytes used to hold the variable. The actual number of bytes used depends on the computer system, except for variables of type char which always hold 1 byte. Characters, for example 'a', are stored in variables of type char, while integers, such as 47, are held in int variables. Declaration of integers and characters appear as:

int iNumber; 

char cCharacter;

The following code fragment illustrates the use of variables. First the source code allocates two areas of memory to hold integer values:

int iFirstNumber;

int iSecondNumber;

Next, the fist variable is assigned the value 17. Then the contents of the first variable are copied to the second:

iFirstNumber = 17;

iSecondNumber = iFirstNumber;

which has the effect of allocating the value 17 to both variables.

Within programs it is often necessary to refer to constant (or literal) values, such as p or the name of a person. Unlike variables, constants can not be changed by the operation of a program - they are fixed until the source code is changed and re-compiled. For example, the following code fragment sets the variable fDiameter to fRadius multiplied by 3.142. No matter what value is contained in fRadius the program will always use a multiplier of 3.142, the only way to change this is to modify the source code and recompile the program.

float fDiameter;

float fRadius;

...

fDiameter = 3.142 * fRadius

Besides including real values, such as 3.142, in source code it is possible to declare variables as constants through the const keyword. Such variables are assigned a value at creation, but can not be changed later, for example:

float fDiameter;

const float fPi = 3.142;

float fRadius;

...

fDiameter = fPi * fRadius

When writing programs it is often necessary to handle characters and strings. A char is a single byte used to store a numeric representation of a character, for example the character 'A' would be stored in the variable as 65, B as 66, etc. The following code declares a character variable and loads it with the letter 'A':

char cCharacter;

cCharacter = 'A';

Note that the variable is assigned the value 'A', letters in '' are treated as characters. It is not permissible to have more than one character between ''.

A string is a sequence of characters, for example "Rosetta". C++ does not provide a specific data type to hold strings, instead an array of chars is employed, an array being a series of contiguous memory locations. Arrays can exist for any data type and are denoted by [x], where x is the number of items to store in the array. The following code declares an array of 10 characters and loads it with some text, note strcpy is a function provided by string.h:

#include 

...

char cCharacters [10];

strcpy (cCharacters, "Rosetta");

In the example above the function strcpy copies the contents of a string literal ("Rosetta") to a string variable (cCharacters). The double quotes indicate to the compiler that a string is being referenced (remember, single quotes indicate a single character).

Write and use functions

All executable code within C++ programs are contained within functions. Even the simplest programs, as outlined above, contain at least one function called main (). The main function is the entry point to all C++ programs, but is not supplied by the compiler - a developer must provide it.

A function is typically a short piece of named code (sometimes referred to as a routine) which performs a simple, well defined action such as taking two numbers, multiplying them together and returning the result to the calling code. Functions may call other functions (or even themselves) but may not contain the definitions of other functions within themselves.

All functions, other than main (), must be known to the compiler before they are used within a source file. Unfortunately this is not always possible, either because you do not have access to the source code which defines the function (as in the case of library functions) or because you do not wish to place the function before it is first used within a file. To solve this problem C++ permits the use of function prototypes. A function prototype describes the function to the compiler, but does not actually provide the implementation - it is an indication of what is to follow. Note, when including header files for libraries (e.g. iostream.h) the developer is providing a number of function prototypes (they are contained by the header file, the preprocessor expanding them into the source file).

Supposing we have a function that displays a message on the screen. The function takes no parameters and returns no value, its prototype would thus be:

void vDisplayMessage ();

The ; immediately after the closing bracket indicates that this is a prototype. If there was an opening { then this would be the start of the function definition itself and not just a prototype.

Over time the requirements of vDisplayMessage change, it must now be capable of taking a parameter (in this case a number). This number will indicate which message to display (1 for "hello", 2 for "goodbye"). The function prototype changes to:

void vDisplayMessage (int iMessageNumber);

If the function prototype and definition are modified, but uses of it with the program are not changed, the compiler will generate compilation errors until the usage matches the definition.

Downloads