As usual, after learning new stuff, I write on it. Yesterday I finished learning on "Functions in C++" and found that functions are very easy to learn and useful. Hope this tutorial helps beginners.

What is function?

Sometimes when we want to execute a specific task wherever it's needed, instead of writing the entire code again, we should create a block of code that is called a function. Once you define the functionality inside the function body, you can call it whenever and wherever it's needed.
Functions prevent code repetition.

There are 2 terminologies:

  1. Defining a function: process of creating functionality
  2. Calling a function: process of executing functionality

Function is a subprogram / block of code which is responsible for a specific task.
We can divide functions in 2 major part:

  1. Library function
  2. User defined function (UDF, further in this tutorial, I’ll use this term instead of "user defined function")

In this tutorial, I'm not covering library functions. I don’t think that library functions require a tutorial, because library functions are readymade code, you need to add header files where these functions are defined and just call them. It's very easy.

Example: to calculate the length of a string, you need std::strlen() function and this is defined in cstring header file.

User defined functions are those function that user creates for a specific purpose.
For example, if you are creating an application which allows a user to issue maximum of 6 books, with 6 boxes for book numbers. Once you fill up one box, the status bar gets updated with the information how many books available for you (like "Now, 5books remaining"), when you fill up another box it gets updated (like "Now 4 books remaining"), and so on. It checks the available books after issuance of each book. So, you need to:

1.Establish the connection with database
2.Select the record(for Remaining Books)
3.Print the result at status bar
4.Close the connection

It will be hard work, and also bad practice, if you write the same code 6 times, so just do smart work and use a function. These aforementioned 4 tasks should be placed in a block called a function. Now you don’t have to write the code 6 times, you just need to call the function 6 times.

Now, I think that you've understood the need for functions (if you are still not getting the concept, just post your question, I'll try to explain it more).

Syntax for function body:

<Return type> <Function Name> (Parameter List with their data type)
{
     // write code , you want to execute
     // write code , you want to execute
     // write code , you want to execute
     return value;
} 

Example

bool IsEven(int num)
{
    if (num%2==0)
        return true;
    else
        return false;
}

Here bool is return type of the function, IsEven is name of the function, and Num is parameter of type int.

Calling this function

int main()
{
    int n;
    bool result;
    cout << "enter a number";
    cin >> n;
    result = IsEven(n); //this is a way to call a function
    return 0;
}

We can pass parameters to a function in two ways:

  1. pass by value
  2. pass by reference

When calling a function, if we pass value(s), then it's pass by value. Like IsEven(n), here we pass the value of n, that's why it's pass by value method.
When we pass address / reference, then it's pass by reference. Like IsEven(&n), here we pass the address of n instead of n itself.
I'll discuss more on these in my next tutorial (related to pointers)

On the basis of parameters / arguments and return type, we can classify the UDF in following categories:

  1. No Arguments And No Return Type
  2. No Arguments And Return Type
  3. Arguments And No Return Type
  4. Arguments And Return Type

Before explaining these types of function, here I make it clear what argument is?
Argument is the information that you pass to the function.
Example: Check_Prime(3); here Check_Prime is function name and value inside brackets (3) is the argument. Arguments are also called Parameters.

When you return nothing then you should place void. If you don’t do this, then by default it's return type is int.

No Arguments And No Return

void IsEven()       //defining a function
{
    int n;
    cout << "enter a number";
    cin >> n;
    if( n % 2 == 0 )
        cout << "its even value";
    else
        cout << "its Odd Value";
}

int main()
{
    IsEven();   //function calling
    return 0;
}

Explanation: I think there is no need to explain.

No Argument and returns

bool IsEven()       //defining a function
{
    int n;
    cout << "enter a number";
    cin >> n;
    if( n % 2 == 0 )
        return true;
    else
        return false;
}

int main()
{
    bool result;
    Result = IsEven();  //function calling
    // if the result is true then print even otherwise odd
    return 0;
}

Explanation: IsEven is called and it returns either true / false and the result is used to store the returned value.

Arguments And No Return

void Big_Value(int x, int y, int z)     //defining a function
{
    if( x > y && x > z )
        cout << x << " is big";
    else if(y>x && y>z)
        cout << y << " is big";
    else
        cout << z << " is big";
}

int main()
{
    bool result;
    Big_Value(3,4,5);   //function calling
    // if the result is true then print even otherwise odd
    return 0;
}

Explanation: It will assign 3, 4, 5 to x, y, z, respectively. Nothing else to explain.

Arguments And Return

int Big_Value(int x, int y, int z)
{
    if ( x > y && x > z )
        return x;
    else if( y > x && y > z )
        return y;
    else
        return z;
}

int main()
{
    int x, y, z, bin_number;
    cout << "enter three values";
    cin >> x >> y >> z;
    Big_number = Big_Value(x, y, z);
    cout << big_number << " is big value";
    return 0;
}

Explanation: Nothing to explain. It's easy. But feel free to ask your questions.

Passing Array as Function Argument: I think it's not possible to pass entire array as function argument, just pass array name. Actually, it's the address of the first element of the array.

#include<iostream>

using namespace std;

void incre_10(int arr[],int SIZE); //its function prototype / its function declaration 

int main()
{
    int a[10];
    const int SIZE=10;
    for(int i = 0; i < 10; i++)
    {
        cout << "enter value=";
        cin >> a[i];
    }
    incre_10(a, SIZE); //here we’re passing the address of the first element of an array named a
    for(int i = 0; i < 10; i++)
    {
        cout << a[i] << endl;
    }
    return 0;
}

void incre_10(int arr[], int SIZE)
{
    for(int i = 0; i < SIZE; i++)
    {
        arr[i] += 10;
    }
}

I welcome your feedback on this tutorial. I’ll cover some aspect of function with pointers in my next tutorial.

Edited 2 Years Ago by Dani: Corrected grammar and code indentations

precise and informative, hope you also know the way for getting two results back from a single function call.

No Argument and returns
bool result;
Result = IsEven();

should be
bool result;
result = IsEven(); <==============

Arguments And Return
int x, y, z, bin_number;
cout << "enter three values";
cin >> x >> y >> z;
Big_number = Big_Value(x, y, z);
cout << big_number << " is big value";

should be
int x, y, z, big_number; <==================
cout << "enter three values";
cin >> x >> y >> z;
Big_number = Big_Value(x, y, z);
cout << big_number << " is big value";

Sorry, and....
should be
int x, y, z, big_number; <==================
cout << "enter three values";
cin >> x >> y >> z;
big_number = Big_Value(x, y, z); <==================
cout << big_number << " is big value";

agree with you. here , bin_number should be read as big_number.
and don't sweat the small stuff.

Its been nice to go through your post.
It has given me much knowledge & so many valuable information.

I'm feeling very nice to be here. so enjoyable...

Edited 2 Years Ago by joo003464: some mistake

happy to see that somebody is really learning with my tutorials , its my great pleasure.

however , Now , i see that this tutorial is not complete . a few topics(like passing array , returning multiple values , call by reference etc). i'll add these here soon.

Great tutorial,Realy informative and great for beginners.

You really did well on explaining functions in general.
Also i like that you pointed out the return types.
They mostly end up further in the books.

Keep up the good work mate!

i have a question sir
in arguments and return part, if the first condition is true then x is returned to the main function with the value it carries?

in arguments and return part, if the first condition is true then x is returned to the main function with the value it carries?

It will return x if x is greater than y and z.And Yes, value of x will be returned to the main in this case.

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.