First Next Previous Last Glossary About

Functions in C++


Introduction

Although this is only the third week of the course it is never too soon to introduce something as important as the function. The sooner you learn how to write functions the sooner you can write more powerful programs.

C++ is like many other structured languages in that it it permits the definition of functions (like Pascal). A function is simply a subroutine which can, if required, return a single value to the caller (the part of the program which invoked the function).

The strength of functions lies in the fact that they are basically programs within the program. We write functions for two major reasons:

  1. To provide for frequently used operations that can be accessed by many programs or from many points within a single program.
  2. To "modularise" complex programs and make the maintenance and understanding of such programs easier.

Return to top of page

Structure of functions

Functions are structured this way:

data_type function_name ( argument declarations )
{   FUNCTION_BODY; }
data_type
The data type of the value returned by the function
function_name
What the function is called
argument declarations
Declarations concerning the data types of the function arguments
function_body
The function code or what it does.

Return to top of page

An example

An example:

Program Comments
//ex14.cc
#include <iostream>
int sumxy(int x,int y);

This is the function prototype.

int main()
{  int total,i;

   total = 0;
   for (i = 0; i <= 10; i++) {
     total = sumxy(i, i + 1);
    cout << total << endl;      
   }
   return 0;
}

The main function, every program has one.

Variables total and i are local to main.

The for loop calls sumxy with two parameters, i and i +1 then prints the running total.

main returns 0 in this case but could return something else.

int sumxy(int x,int y)
{ int temp;

  temp = x + y;
  return temp;
}

A function of type int which has two arguments x and y which are of type int.

A local variable temp of type int is declared and the value of temp is returned to the caller.

A function need not return a value, it can be declared as being of type void:

void pf(float a,float b)
{ cout <<  (a * b);
}

A function need not have any arguments:

void pf(void)
{ float a = 12.46, b = 98.098;
  cout <<  (a * b);
}

Return to top of page

Functions and function arguments

Usually we use functions with arguments or parameters and whenever we use functions we must make some reference to the function declaration before we use it. The usual way in C++ is to declare a function prototype. You would have seen that in the example just back half a page. The function int sumxy(int x,int y); is declared well before we use it. The function is defined later, after the main function.

It isn't absolutely necessary to use function prototypes, you could declare and define at the same time but most people use prototypes. If you ever to get to work on larger projects and/or write and sell programming libraries for a living you will discover why.

The function arguments in the definition and the declaration are called the formal arguments or formal parameters. When the functions are invoked (called) then the program supplies actual parameters.

Program Comments
//ex14.cc
#include <iostream>
int get_func(int a, int b);
void state_size(int a, int b);
void state_size_v2(char, int , char , int );
Here are the prototypes with the formal parameters or arguments. Notice that we don't have to give a name to each argument but the type must be known.
int main()
{ int x,y,z;

  cout << "Enter an integer value for x ";
  cin >> x;
  cout << "Enter an integer value for y ";
  cin >> y;
   
  z = get_func(x,y);
  cout << z << endl;  

  state_size(x,y);
  cout << endl;
  state_size_v2('x',x,'y',y);  
  return 0;
}
Call the functions. Since get_func returns a value we assign its result to z. Both the state_size functions are void, ie they don't return anything. This is where the actual arguments occur.
void state_size_v2(char m, int a, char n, int b)
{if (a> b)
  cout << m << " is larger than " << n;
 else
  cout << m << " is not larger than " << n;
 cout << endl;
 if (a > b)
  cout << m << " is larger than " << n;
 else
  if (b > a)
   cout << n << " is larger than " << m;
  else
   cout << m << " and " << n << " are the same";
}
See how the arguments match up. char with char, int with int. The call to function state_size_v2('x',x,'y',y); has four actual arguments which match the four formal arguments of the function.
void state_size(int a, int b)
{if (a > b) cout << "a is larger than b";
 else cout << "a is not larger than b";
 cout << endl;
 if (a > b) cout << "a is larger than b";
 else if (b > a)
       cout << "b is larger than a";
      else cout << "a and b are the same";
}
function state_size() is a void function, it doesn't return a value.
int get_func(int a, int b)
{ return a * (b + 4); }
This function uses the return statement, ie return a value to the caller. The return statement can handle an expression.

Return to top of page

C and C++ standard functions

C and C++ contain many useful inbuilt functions designed to provide for all kinds of commonly occurring situations, for example:

Maths functions (note well: parameters are type double and each function returns a type double. sin, cos and tan are radians):

sqrt(arg_a)
return the square root of arg_a
log10(arg_a)
return log base 10 of arg_a
sin(arg_a)
return the sine of arg_a
cos(arg_a)
return the cosine of arg_a
tan(arg_a)
return the tangent of arg_a
pow(arg_a,arg_b)
return arg_a raised to the power arg_b

Date and time functions (parameter x is type time_t which is basically a long integer):

time(x)
return the time in parameter x (in seconds since some date in 1970)
clock(void)
get the number of clock ticks that have expired since the program started

Here is some mild lunacy with time:

//ex12a.cc
#include <iostream>
#include <time.h>

#define DAYS       365
#define HOURS       24
#define SECONDS   3600

int main()
{
 time_t the_time;
 clock_t ticks;

 the_time = time(&the_time);

 cout << "It has been " 
      << (double) the_time/(DAYS * HOURS * SECONDS) 
      << " years since UNIX time began" 
      << " (give or take a few days)."
      << endl;
 return 0;

}

and an example using the pow function:

//ex12b.cc
#include <iostream>
#include <math.h>     //some compilers automatically
                      //include math.h

int main()
{
 double a = 4.0 ,b = 3.0;

 cout << a << " raised to the power "
      << b << " is "
      << pow(a,b) << endl; 
 return 0;
}

There are many different and useful "standard" functions but you will need to know how to write some of your own for those special occasions. You can read about the functions available in The GNU C Library here, but it can be a bit of an intimidating read for the beginner.

Return to top of page

Tutorial 4 Functions

  1. The sin, cos and tan functions all deal in radians, ie the arguments are in radians and the result is in radians. A radian is a unit of circular measure, like a degree but bigger. There are approximately 57º in a radian. Write a function which converts degrees to radians and a function that converts radians to degrees.
  2. If you use a laser distance measuring device you can measure the heights of things. To get the height you use the formula:

    height = distance * sin(elevation);

    distance is the line of sight distance measured by the laser and elevation is the angle at which the laser was tilted.
    1. Write a function which calculates height in metres given distance and elevation. Assume the elevation is given in degrees and you have to use the function from part 1. The distance is in metres.
    2. Your new laser breaks down but you have an old laser which measures in yards. Write a function to convert the results from the old laser to metres. There 2.54 centimetres to the inch, 36 inchs to the yard and 100 centimetres to the metre.
    3. You have to take the old laser to sea and it has been recalibrated to nautical miles. There are 6080 feet to the nautical mile, 12 inches to the foot and 1760 yards to the statute mile. There are 3 feet to the yard. Write a function which converts from nautical miles to yards. Use this function in a program which displays height in metres using the function from 2b. Assume elevation is in degrees.

There is a sample solution to these here!

Return to top of page


First Next Previous Last Glossary About


Copyright © 1999 - 2001 David Beech