Functions

  • A function is a subroutine that contains one or more C++ statements and performs a specific task.
  • Every program that you have written so far has used one function: main( ).
  • They are called the building blocks of C++ because a program is a collection of functions.
  • All of the “action” statements of a program are found within functions.
  • Thus, a function contains the statements that you typically think of as being the executable part of a program. Although very simple programs, such as many of those shown in this book, will have only a main( ) function, most programs will contain several functions. In fact, a large, commercial program will define hundreds of functions.

The Function Declaration

  • Just as you can’t use a variable without first telling the compiler what it is, you also can’t use a function without telling the compiler about it.
  • Function declarations are also called prototypes, since they provide a model or blueprint for the function.
 void starline();

Calling the Function

The function is called (or invoked, or executed) three times from main(). Each of the three calls looks like this:

 starline();

The Function Definition

  • The definition consists of a line called the declarator, followed by the function body.
  • The function body is composed of the statements that make up the function, delimited by braces.
 void starline() //declarator 
  { 
   for(int j=0; j<45; j++) //function body 
     cout << ‘*’;
   cout << endl;
  }

Passing Pointers to Functions

  • To pass a pointer as an argument, you must declare the parameter as a pointer type.
 // Pass a pointer to a function.
#include <iostream>
using namespace std;

void f(int *j);

int main()
{
   int i;
   f(&i);
   cout << i;
   return 0;
}

void f(int *j)
{
  *j =100; //var pointed to by j is assigned 100
} 

Passing an Array

  • When an array is an argument to a function, the address of the first element of the array is passed, not a copy of the entire array. (Recall that an array name without any index is a pointer to the first element in the array.)
  • This means that the parameter declaration must be of a compatible type.
// Pass a pointer to a function.
#include <iostream>
using namespace std;

void display(int num[10]);

int main()
{
  int t[10], t;
  for(i=0; i<10; ++t)
    t[i]=i;
  display(t); // pass array t to a function
  return 0;

//Print some number.
void display(int num[10]) // Parameter declared as a sized array
{
  int i;
  for(i=0; i <10; i++)
  cout << num[i] << ' ';
}