C++ – Functions

Functions allow to structure programs in segments of code to perform individual tasks.

Functions with type

Working samples:


// function example
#include <iostream>
using namespace std;

// integer - name of the function - data
int addition (int a, int b)
{
  int r;
  r=a+b;
  return r;
}

int main ()
{
  int z;
  z = addition (5,3);
  cout << "The result is " << z; // the result is 8
}


// function example
#include <iostream>
using namespace std;

int subtraction (int a, int b)
{
  int r;
  r=a-b;
  return r;
}

int main ()
{
  int x=5, y=3, z;
  z = subtraction (7,2);
  cout << "The first result is " << z << '\n';
  cout << "The second result is " << subtraction (7,2) << '\n';
  cout << "The third result is " << subtraction (x,y) << '\n';
  z= 4 + subtraction (x,y);
  cout << "The fourth result is " << z << '\n';
}

Functions with no type – void


// void function example
#include <iostream>
using namespace std;

void printmessage ()
{
  cout << "I'm a function!"; // it prints 'I'm a function!'
}

int main ()
{
  printmessage ();
}

Arguments passed by reference

// passing parameters by reference
#include <iostream>
using namespace std;

void duplicate (int& a, int& b, int& c)
{
  a*=2;
  b*=2;
  c*=2;
}

int main ()
{
  int x=1, y=3, z=7;
  duplicate (x, y, z);
  cout << "x=" << x << ", y=" << y << ", z=" << z;
  return 0;
}

The result:
x=2, y=6, z=14