In order to form an immaculate member of a flock of sheep one must, above
all, be a sheep.

— Albert Einstein

C++ Functions

General form

All the C++ functions share the same general form

return-type function-name (list-of-parameters) {
//function-body
}

  • return-type is any valid type except for the array. If the function does not return any value its return-type must be void.
  • function-name any legal identifier which is not already in use.
  • list-of-parameters is the sequence of data-type variable-name separated by the comma separator. Parameters are essentially the values of the variables passed to the function when is being called. If the function has 0 parameters than the list of parameters is empty.
  • function-body is composition of C++ statements describing what this function does.

How to create function?

To create function in C++ is very easy as all of them share the same general form.
Lets see some example of code and see what exactly happens:


#include
using namespace std;
void sayHi(int level); //function prototype
int main()
{
cout << "1st Hi from main.\n"; //1st message on the main
sayHi(0); //function call
cout << "2nd Hi from main.\n"; //2nd message on the main
return 0;
}
void sayHi(int level){
cout << "Hi from inner function and level " << level << ".\n";
if (level<5){ //if the level is less then 5
return sayHi(++level); //make recursive call (return void)
}else{
return; //return void (terminate)
}
}

The output of this program is:

1st Hi from main.
Hi from inner function and level 0.
Hi from inner function and level 1.
Hi from inner function and level 2.
Hi from inner function and level 3.
Hi from inner function and level 4.
Hi from inner function and level 5.
2nd Hi from main.

  • Function must be declared before first call.
  • The function prototype declares the function sayHi() to have void return-type what formally states that function has no return value and one input parameter of type int.
  • All functions must have prototype except for the function main.