Predefined Functions

  1. C++ has a library of predefined functions. Appendix 4 has a list of some of these predefined functions.

  2. The syntax of a predefined function is:

    Function_Name(Parameter1, Parameter2, ...)

    where Function_Name is the name of the function, and Parameter1 is the first parameter of the function, Parameter2 is its second parameter, etc.

  3. A predefined function may have zero, one or more parameters.

  4. Be careful about the actual number of parameters a function has, and the types of values the parameters can take on, and restrictions or assumptions for the parameter values and the returned value.

  5. A function is used (called) by supplying the function name together with values for the parameters of the function enclosed by parentheses and separated from each other by commas. The parentheses cannot be omitted even if the function has no parameters. For example the function that generates a random integer: rand( ).

  6. Each of the predefined function returns a single value of a specific type when it is called.

  7. To use these functions, the appropriate header files must be included using preprocessor directives. For example the above rand function requires the directive: #include <cstdlib>.

  8. Another example is the function sqrt(x), which has a parameter, x, of type double. It returns the square root of x, also of type double. That function is defined in the header file cmath and so one has to use the preprocessor directive: #include <cmath>. The actual argument used must not be negative, and only the positive square root is returned.

  9. Another useful predefined function is pow(a,b), which computes a raised to the b power. Note that an error will occur if a=0 and b is negative, or if a is negative and b is not an integer.

  10. The actual arguments supplied to the function when it is called, can be literal constants, variables or expressions, provided their types agree with those assumed of the function parameters, and the variable or expression has a value.

  11. Example how to use predefined functions and constants:

    #include <iostream>
    #include <cmath>
    using namespace std;

    int main ( )
    {
         const double PI = 3.141592653589793;
         double area, diameter;
         cout << "Enter the area of the pizza in square inches : ";
         cin >> area;
         diameter = 2.0 * sqrt(area/PI);
         cout << "The pizza has a diameter of :" << diameter << endl;

         return 0;
    } //end main