Next: Functions that return values Up: Introduction to User-defined functions Previous: Functions with no parameters

Functions with parameters and no return value

The function of the previous section is not very useful, what if four lines were to be skipped, or two lines? It would be much more useful if it was possible to tell the function how many lines to skip. That is the function should have an input parameter which indicates how many lines should be skipped.

The function skipthree() is now changed to the function skip which has a parameter n indicating how many lines have to be skipped as follows:

void skip(int n)
   // Function skips n lines on output
  {
    int i;   // a local variable to this function
      // now loop n times
    for (i = 0; i < n; i++)
      cout << endl;
  }
Download program.

As before this function does not return a value hence it is declared as having type void. It now takes an integer parameter n which indicates the number of lines to be skipped. The parameter list then consists of a type and a name for this formal parameter. Inside the body of the function (enclosed in {}) a loop control variable i is declared. This variable is a local variable to the function. A local variable defined within the body of the function has no meaning, or value, except within the body of the function. It can use an identifier name that is used elsewhere in the program without there being any confusion with that variable. Thus changing the value of the local variable i in the function skip will not affect the value of any other variable i used elsewhere in the program. Similarly changing the value of a variable i used elsewhere in the program will not affect the value of the local variable i in skip.

The function is called in the same manner as skipthree() above, but a value must be given for the parameter n. Thus all the following calls are acceptable:

void main()
{
  int m = 6, n = 3;
  ...............;
  skip(m);
  .......;
  skip(m + n);
  ............;
  skip(4);
  .......;
}
however the call:
skip (4.0);
would not be acceptable because the actual parameter type must match the formal parameter type given in the definition of the function.

In writing the function prototype for a function with parameters it is not necessary to detail the formal names given to the parameters of the function, only their types. Thus a suitable function prototype for the parameterised version of skip would be:

void skip(int); // function prototype



Next: Functions that return values Up: Introduction to User-defined functions Previous: Functions with no parameters