C++ quick-reference

C++ is an imperative language with built in support for object oriented programming.

Many of the features of the language are illustrated below, but it is mostly description by example - there isn't much text.


Program layout (recommended)

Following the layout shown below eliminates many potential problems - mostly with respect to using identifiers (for constants, variables, types, or functions) before the relevant construct has been declared.

  1. Pre-processor statements (e.g. #include statements)

  2. Constant definitions

  3. Type definitions

  4. Function declarations

  5. Main function
    1. main header
    2. variable declarations
    3. statements

  6. Function bodies
    1. function header
    2. variable declarations
    3. statements
    The key feature is that variables, constants, types, and subroutines must be declared somewhere "above" their first actual use in the program.

    Note that most statements are terminated with a semicolon, and that // is the comment symbol - everything to the right of the double slash is ignored by the compiler Example:

    // include the io library
    #include <iostream>
    
    // specify the namespace we are using
    using namespace std;
    
    // declare a constant size to be used for arrays
    const int SIZE = 20;
    
    // declare floatarray as a type describing arrays
    //   of "SIZE" floating point elements
    typedef float floatarray[SIZE];
    
    // declare a subroutine, printarray, which takes a
    //    floatarray as a parameter 
    void printarray(floatarray arr);
    
    // provide the main body of the program
    int main()
    {
       floatarray myarray;
       for (int index = 0; index < SIZE; index++) {
           myarray[index] = index * 1.5;
       }
       printarray(myarray);
    }
    
    // provide the body of the printarray subroutine
    //    declared earlier
    void printarray(floatarray arr)
    {
       for (int index = 0; index < SIZE; index++) {
           cout << arr[index] << endl;
       }
    }
    

Data types and conversions


Variables, constants, and scope