Home / code / cpp

C++ functions

Functions are divided in 2 main forms. Those that deliver a result (mostly int) and those that do not (void).

Here are some tips for writting functions:

  • Think a name for the function that resambles what is does.
  • Make a function as flexible as possible, so you can use it in many different situations.
  • Does the function need arguments?
  • Should the function return a value?

Example
#include <iostream.h>

void Square();   //prototype of the function

void main()
{
  cout << "Call the function: " << endl;
  Square();   //calling the function
  cout << "The function is completed";
  cin.get();
}

void Square()    //Definition of the function
{
  int r, k;
  for (k=1;k<=17;k++) cout << 'x';
  cout << endl;

  for (r=2;r<=4;r++)
  {
    cout << 'x';
    for (k=2;k<=16;k++) cout << ' ';
    cout << 'x' << endl;
  }

  for (k=1;k<=17;k++) cout << 'x';
  cout << endl;
}

This is a simple program with a function that draws a square.

There are 3 important parts here:

  • void Square(); The prototype of the function is obligated, unless the definition of the function is positioned before you call the function.
  • Square(); Calling of the function, you can call the function as many times as you wish. It is made for that.
  • void Square() {...} The definition of the function. What the function should do when it is called.

Functions with arguments

The previous function, Square() can only draw squares of 17x5. The same function with arguments can draw squares of all sizes.

We add to arguments of the type int:

void Square( int width, in height );
of course you have to change the body of the function a bit.
void Square( int width, in height )
{
  int r, k;
  for (k=1;k<=width;k++) cout << 'x';
  cout << endl;

  for (r=2;r<=(height-1);r++)
  {
    cout << 'x';
    for (k=2;k<=(width-1);k++) cout << ' ';
    cout << 'x' << endl;
  }

  for (k=1;k<=width;k++) cout << 'x';
  cout << endl;
}
And now you can call the function:
Square(8,3);
or any other combination.

Default arguments

You can also use default arguments, so you don't always have to add arguments when you call the function.

void Line( int width=10 )  //function with default argument
{
  for ( int k=1;k <= width; k++) cout << 'x';
  cout << endl;
}
So now you can call the function in 2 ways:
Line(); there will be 10 x 's.
Line(15); there will be 15 x's.

In a function with more then 1 argument can have several default arguments, but: they must always be at the end of the list.

void Something(int a, char b, int c=9) //allowed
void Something(int a, int b=8,int c) //NOT allowed

Functions that return a value (int, double, ...)

A function can return values. This value can be a number like int or double, but it can also be a char or a other type.

Example
double average( double a, double b)
{
  double g=(a+b)/2;
  return g;
}

The previous function returns the value g of the type double.
The value that comes after return is the value that is returned by the function.

You can make the function a bit shorter.

double average( double a, double b)
{
  return (a+b)/2;
}

You can have more then 1 return in a function, BUT there will be only 1 value returned.

Example
#include <iostream.h>
char Capitalchar( char ch_in);

void main()
{
  char ch;
  cout << "Enter characters (point will stop):" << endl;
  do
  {
	cin >> ch;
	ch = Capitalchar( ch );
	cout << ch;
  } while ( ch !='.');

  cin.get();

  cout << endl << "End program";
  cin.get();
}

char Capitalchar( char ch_in )
{
  if(ch_in >='a' && ch_in<='z')
  {
	return ch_in -32;
  }
  else
  {
	return ch_in;
  }
}

The variables

Variables declared in a function are, like the arguments of the function, local variables.
They are created when the function starts and destroyed when the function ends.
So you can't use the variables of the function outside the function.

You can change this with static. When you place static for the declaration of the variable, the variable is created at the start of the program and stays 'alive' and holds its value until the program ends.

Example:
#include <iostream.h>
#include <iomanip.h>

double Average(double number);

void main()
{
  double number;

  cout <<"Enter numbers         ";
  cout <<"Average of all the numbers until now:" << endl;
  cout <<"(0 to stop)" << endl;

  do
  {
	cin >> number;
	if (number != 0.0) cout << setw(40) << Average( number ) << endl;
  }while(getal != 0.0);
}

double Average(double number)
{
  static int count=0;  //static variables
  static double sum=0.0;

  count++;
  sum+=number;
  return sum/count;
}

As you can see the function is called upon several times but count and sum never loose their value.

Global variables

Global variables are variables that can be used in all the functions (including the main function).
If you create a local variable and a global variable with the same name, the local variablehas priority.

Example:
#include <iostream.h>

int year=1990;  //global variable

void Century();

void main()
{
  Century();
  cout << year << endl;
  cin.get();
}

void Century()
{
  int year=2000;  //local variable
  cout << year << endl;
}

The result looks like: 2000
1990

Reference argument

With reference argument you can not only pass the value of a variable, but the variable itself to a function.
You can transfer a local variable from 1 function to another.

Example:
#include <iostream.h>

void request_s(double & gift);

void main()
{
  double amount=0.0;

  request_s( amount );
  cout << "The donation is: " << amount << endl;
  cin.get();
}

void request_s( double & gift )
{
  cout << "How much are you willing to spend ?" << endl;
  cin >> gift;
  cin.get();
}

In the example gift is the reference argument. You can see this by the '&'-character.

void request_s(double & gift);

When we call the function with amount:

double amount=0.0;
gift becomes a alias for amount. This means that when gift gets a value, it is actual amount that gets the value.

A function that delivers a reference

Study the following examples;

  • The first is done with return by value (The function delivers a value).
  • The second is done with return by reference (The function returns a reference to a variable)

#include <iostream.h>

int max(int a, int b)
{
  if (a > b) return a;
  else return b;
}

void main()
{
  int x=20, y=100, g;

  g=max(x,y);

  cout << "The largest number is "<< g;
  cin.get();
}

The result will be of course: The largest number is 100

#include <iostream.h>

int & max(int & a, int & b)
{
  if (a > b) return a;
  else return b;
}

void main()
{
  int x=20, y=100, g;

  g=max(x,y);

  cout << "The largest number is "<< g;
  cin.get();
}

The difference between the 2 programs are the ampersands (&) on line #3. The output of the 2 programs is identical.
Still there is a big difference: in the first example the function returns the value 100, in the second example the function returns the variable y.

Function overloading

In most program languages the name of the function must be unique. Not in C++.
In c++ you can have several function with the same name, but there has to be difference between the number of arguments and the type used.

Example : The following example has 3 overloaded functions.
#include <iostream.h>

double surface( double a );
double surface( double a, double b );
double surface( double a, double b, double height );

void main()
{
  double x=3.0, y=5.5, h=.5;

  cout << "Square of << x <<" by "<< x <<": ";
  cout << surface(x) << endl;

  cout << "Square of << x <<" by "<< y <<": ";
  cout << surface(x, y) << endl;

  cout << "Square of << x <<" by "<< y <<": ";
  cout << surface(x, y, h) << endl;

  cin.get();
}

double surface( double a )
{
  return a*a;
}

double surface( double a, double b )
{
  return a*b;
}

double surface( double a, double b, double height )
{
  return (a+b)/2*height;
}
Another example:
#include <iostream.h>

void test( double a );
void test( int a );

void main()
{
  test(5);
  test(5.5);

  cin.get();
}

void test( int a )
{
  cout << "This is a int " << a << end;
}

void test( int a )
{
  cout << "This is a double " << a << end;
}

 

TOP

Latest script:

 

Books: