Minimal Description of a C/C++ Program

Basically a C or C++ program consists of a set of source code files (.c or .cpp) and header files (.h), which are compiled by a compiler to produce object modules (.obj). These are linked by a linker to produce an executable (.exe) program.

Source code files consist of:

1. Comments: // ... for one line or /* ... */ for multi-line.

2. #include directives for including header files, e.g. #include <math.h>

3. #define directives, e.g. #define TRUE 1 and #define FALSE 0

4. Function declarations, e.g. int get_yn_answer(char* question);

5. Function definitions

1 - 4 are sometimes collected into a separate header file, especially if the same statements will be used by many source code files.


C code mostly occurs within function definitions and consists of statements, which may be classified as follows:

1. Variable declarations, e.g. int i, char answer, double x; char *question is C-style declaration, char* question is C++ style.

2. Assignments, e.g. i = 3, j = int(sqrt(x));

3. In C++: Stream input/output, e.g. cout << question << endl; cin >> answer;

4. Repetition statements

for

    for ( i=0; i<n; i++)
        { ... }
while
    while ( i < n )
        { ... }
do ... while
    do
        { ... } while ( i < n );

5. Program control statements

if

    if ( i > j )
        { ... }
if ... else
    if ( i > j )
        { ... }
    else
        { ... }
switch
    switch ( i )
        {
        case 0: ... break;
        case 1: ... break;
        ...
        default:
        }

6. Function calls, e.g. process_data();


A C/C++ program always begins with a function called main(). The program essentially consists of functions which call other functions which call other functions, and so on. Often the next step in a program depends on the result returned by the last-called function. This hierarchical execution of functions is carried out until (normally) all statements in the main function have been executed.