Functions in c++


  • 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.

Function declaration

  • A function has a name and a type, much like a variable. The function’s type is defined by its return value, that is, the value the function passes back to the program.
  • In addition, the type of arguments required by a function is important. When a function is declared, the compiler must therefore be provided with information on
    • the name and type of the function and
    • the type of each argument.
    Example:
     int toupper(int);
    double pow(double, double);
  • This informs the compiler that the function toupper() is of type int, i.e. its return value is of type int, and it expects an argument of type int.
  • The second function pow() is of type double and two arguments of type double must be passed to the function when it is called.
  • The types of the arguments may be followed by names, however, the names are viewed as a comment only.

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] << ' ';
    }