Tutorial for understanding the C++ functions. It shows you two functions that return the same result but are coded differently.
We have the function:
// Creating a function and using it. Doesn’t use return.
#include <iostream>
using namespace std;
void square(int i);
int main(void)
{
int num;
cout << "Please enter a number: ";
cin >> num;
square(num);
return 0;
}
void square(int i)
{
int sq = i * i;
cout << "Square of " << i << " is " << sq;
}
Let’s see how this works:
void square
-first we create the prototype of the function. We use ‘void’ because we don’t want the function to return any value (if we don’t use void and we don’t return any value, the compile will return an error).
int i – the type of the argument we will use to hold the number we want to be multiplied. ‘i’ is the name of the argument variable.
square(num);
– we use the function to display the square of the number in the ‘num’ variable.
After the ‘main’ function ends, the definition of the ‘square’ function begins. We use the ‘i’ variable (the argument) to be multiplied and stored in a variable which is then displayed using ‘cout’. Using this function is the same as inserting the code inside it instead of the call of the function, ‘square(num)’.
This function does the same thing, but works differently. It doesn’t use ‘cout’ inside the function, but instead it returns a value. That is why this time we don’t use void at the prototype and definition of the function. Instead we use ‘int’, the type of value we expect the function to return.
// Creating a function and using it. Uses return.
#include <iostream>
using namespace std;
int square(int i);
int main(void)
{
int num;
int sq;
cout << "Please enter a number: ";
cin >> num;
sq = square(num);
cout << "Square of " << num << " is " << sq;
return 0;
}
int square(int i)
{
int sq = i * i;
return sq;
}
Depending on the situation, you may want to use the first type of function, or the second.