Functions

 

The purpose of creating a function is so that a block of code can be executed multiple times when a function is called.

 

Data known as parameters is passed into the function.

 

The function main() is predefined and is mandatory in program. However there are other functions which are user defined.

 

How to create a function?

 

Syntax:

void nameFunction()
{
  //code block
}

 

Note: Void means the function doesn't have a return value

 

 

Function Calling

 

To call a function we are to write the function's name followed by brackets () and a semicolon;

 

Example:

 

#include <iostream>

using namespace std;

void myFunction()
{
  cout << "We are learning functions";
}

int main() 
{
  myFunction();
  return 0;
} 

 

 

Output:

We are learning functions

 

Note: The function can be called multiple times and that's what makes it useful.

 

Example

 

#include <iostream>

using namespace std;

void myFunction()
{
  cout << "We are learning functions";
}

int main() 
{
  myFunction();
  myFunction();
  myFunction();

  return 0;
} 


Output:

We are learning functions
We are learning functions
We are learning functions

 

Note: If a user-defined function as in the above example is declared after the main() function the code will throw an error. It is because C++ works from top to bottom in a sequential flow.

 

Hence another way of writing the function, if the function is written below main() is :

 

Example:

 

#include <iostream>

using namespace std;


// Declaration of the Function
void nameFunction();

// Main before the function
int main() {
  nameFunction(); // call the function
  return 0;
}

// Function 
void nameFunction() {
  cout << "We are learning functions";
}