Next: Functions with no parameters Up: Introduction to C++ Programming Previous: Exercises


Introduction to User-defined functions in C++

C++ allows programmers to define their own functions. For example the following is a definition of a function which given the co-ordinates of a point (x,y) will return its distance from the origin.

float distance(float x, float y)
      // Returns the distance of (x, y) from origin
   {
    float dist;  //local variable
    dist = sqrt(x * x + y * y);
    return dist;
   }
Download program.
This function has two input parameters, real values x and y, and returns the distance of the point (x,y) from the origin. In the function a local variable dist is used to temporarily hold the calculated value inside the function.

The general form of a function definition in C++ is as follows:

function-type function-name( parameter-list )
{
local-definitions;
function-implementation;
}



Subsections

Next: Functions with no parameters Up: Introduction to C++ Programming Previous: Exercises