Functions

A group of statement that perform a particular task are known as functions. We have already seen functions, the main() function is an inseparable part of a C++ program. We can define our own functions too. The main() function looks like:

int main() {
//statements
return 0;
}

The return type of a function is declared first which describe the type of data the function is going to return. If the function does not return any value, void is used in place of int. The main function always returns int.

Then the name of the function is declared followed by () which can contain 0 or more parameters. The main function do not contain any parameters.

Example:

#include <iostream>
using namespace std;

int add(int a,int b)
{
    return a+b;
}

void letsprint()
{
    cout<<"The sum is:"<<endl;
}
int main()
{
    letsprint();
    cout<<add(78,98)<<endl;
    return 0;
}

We have defined two functions here add() and letsprint(), the return type of add is int and that of letsprint() is void, which denotes that it do not return any value but just print out the value to screen.

The main advantage of using functions is that they can be used as many times as we want without writing the whole code again and again. You can try this by calling add() function one more time in main().

Default parameters

Functions can contain parameters having a certain default value so that we do not need to give a value every time we call a function. When the value is provided the default value is not used. For example:

int add(int a, int b = 5)
{
return a+b;
}

When you call this function from main().

int main() {
cout<<add(7)<<endl;
cout<<add(4,4)<<endl;
return 0;
}

Output:

12
8

Thus we got a basic knowledge of functions, their uses and advantages. The functions can also simplify big tedious tasks. We will talk about other uses of functions in next chapter. Try making your own functions and have fun. If you have any doubt regarding this lesson, you can ask it in comments. Thank you.

 

 

Leave a comment