Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Functions in C++ (http://www.go4expert.com/articles/functions-in-cpp-t29949/)

usmanmalik 28Dec2013 19:23

Functions in C++
 
During programming, often times we come across situations where we are writing same lines of code again and again. For instance if you write a calculators programming, whenever user wants to calculate sum of two numbers, you will require corresponding statements performing addition. But in a calculator’s program, user can perform addition virtually infinite times. We cannot write code for every addition operation performed by the user in calculator program. So what is the work around here? Yes, you guessed correctly; the C++ functions.

Functions are multiple program statements grouped into a unit. This unit can be called whenever we want in our code. Functions have two basic advantages in C++: Functions help in modularization of the program, it organizes the code. Second biggest benefit of using functions is reusability. As aforementioned in scenarios where same program statements are repeatedly being written. We can group those statements into one function and then call that function in our program wherever we want.

Syntax of Function in C++



Defining a function is an extremely simple task. Have a look at the below lines of code
Code:

void func1()
{
    // Program Statements here
}

Pay attention to the first line, It has three parts:
  1. void
  2. func1
  3. ()
Now let us explain them one by one.

Here the first part i.e. void is the return type of the function. Return type means what a function returns once it has been executed. A function can return any type e.g. an int, char, string etc.

The second part here i.e. func1, is the name of the function. This is the identity of the function and whenever we want to call this function we will call it by this name.

The third and last part, opening parentheses and closing parenthesis are used to pass arguments to the function. We will discuss these concepts in the later part of the tutorial but for now, keep it simple.

After you return type, function name and the argument parenthesis, you place opening and closing braces and inside these braces you write the statements of the function. Statements between the opening and closing braces constitute the body of the function. Any reusable piece of code is placed between these opening and closing braces. Remember, if you are defining function before the main method, you need to place a semicolon at the end of function definition.

Calling a function



The piece of code which calls or invokes the code inside the function body is called the function call. The syntax of a function call is also very easy. You just name the function followed by the opening and closing parentheses. You have to pass arguments if function call requires arguments.

Now we will explain the above concepts with the help of working example.

Note: This code has been written in visual C++, VS 2010, and Win 32 Console application.

Example1
Code:

#include <iostream>
using namespace std;

void func1()  // Function Definition
{
    cout <<"This is the body of the function";

int main()
{
    cout <<"code before the function call"<<endl;
    func1(); // Function call
    cout<<"\nCode after the function";
}

In Example1, we have defined a function named func1 with return type void and no arguments have been passed to this function. In the body of the function we have written one statement which will output the string "This is the body of the function".

Inside the main function, we have first printed a line saying that this is the code before function call, then the function call and then display statement that this is the code after the function call.

It is very important to understand the flow of the code here. Control first enters the main statement, then the following statement executes.

Code:

cout <<"code before the function call"<<endl;
Now when the function is called, control is shifted to the first line of the function that is called. In this case, function call will shift the control from the main function to the func1. The statements inside the function will be executed which is:

Code:

cout <<"This is the body of the function";
After all the statements in the function body are executed, control again returns to the main function and the code below the function call will execute normally. The output of this program will be:

Output1

http://imgs.g4estatic.com/functions-cpp/output1.png

Now the benefit of this code is that whenever we want to print the statements inside the body, we will not have to write them again and again; instead we will simply have to call the function and statement will be executed.

Separate function declaration and definition



There is another way to define the above function. In Example1, we provided complete function definition before the main function. We can also do it the other way. We can only declare the function before the main function and define it after the main function. The result will be same. Example2 explains this concept.

Example 2
Code:

#include <iostream>
using namespace std;

void func1();  // Function Declaration
 
int main()
{
    cout <<"code before the function call"<<endl;
    func1(); // Function call
    cout<<"\nCode after the function";
}

void func1()  // Function Definition
{
    cout <<"This is the body of the function";
}

The output of this program will be similar to the output of Example1. Remember, in case we separate the declaration and definition of the function. We only need to put a semicolon after the declaration not after the definition.

Passing Argument to the function



Till now, we have not kept the argument parentheses empty. In Example1 and Example2 we simple displayed a string in the function body. In this section we are going to explain how you can pass arguments to a function and make use of them. By passing argument to the function you are interacting with a function by passing data to it. Data passed in the function can be used for any purpose inside the function.

In order to pass arguments to the function, first of all we have to define that what type of arguments, a function can accept. We do so by writing the argument type and a parameter name inside the parentheses followed by the function name.

Code:

void func1 (int a, int b);
In the above line of code, we have defined two parameters of type integer. Now in the function call we have to pass two arguments of type integer, otherwise compiler will generate an error.

The function call to this function would be something like

Code:

func1(5, 12);
Now, when this function call executes, 5 and 12 will be stored in the parameters of the function definition and we can access these values through ‘a’ and ‘b’ in the function definition

Code:

void func1 (int a, int b);

Passing Constant to the function as arguments



This concept will be explained by an extremely simple example. We will pass two arguments to a function and function will calculate sum of the function and display it. Have a look at Example3.

Example3
Code:

#include <iostream>
using namespace std;

void sum(int a, int b)  // Function Definition
{
    int result= a+b;
    cout <<"This sum of the arguments is: "<<result;
}

int main()
{
    sum(5,10);
}

In Example3, we have defined a function named sum which accepts two arguments. The function adds the argument passed and displays their sum. In the main function we called this function and passed two constant values 5 and 10 as arguments. The output 15 will be displayed by the sum function as follows:

Output3

http://imgs.g4estatic.com/functions-cpp/output3.png

Passing Variables as Arguments



In Example3 we passed constants as arguments to the function call. We passed 5 and 10. Instead of passing constants, we can also pass variable to function call. Example4 explains this concept.

Example4
Code:

#include <iostream>
using namespace std;

void sum(int a, int b)  // Function Definition
{
        int result= a+b;
        cout <<"This sum of two numbers is: "<<result;
}

int main()
{
        int num1, num2;
        cout<<"Enter the first number:";
        cin>> num1;

        cout<<"Enter the second number:";
        cin >> num2;
        sum(num1,num2);
}

In Example4, it can be seen that we defined two variables num1 and num2 and then we asked the user to input the values which he wants to add. We stored those values in num1 and num2 variable and then in the function call, we passed these two variables. Now the sum calculated by the sum function will be equal to the sum of variables passed in the function call. The output of the function will be.

Output4

http://imgs.g4estatic.com/functions-cpp/output4.png

Returning Values from a function



In all the previous examples, we have been dealing with functions which do not return any data. The return type of such functions is void. Now if we want our function to return something, we will have to change that void in the start of the function definition to the type of data we want to return. Take for example the following function definition.

Code:

int sum(int a, int b);
The above line of code means that a function sum has been declared which requires two arguments of type int and function will return an integer back to the calling function. Inside the function body, at the end of the function we must have to use the keyword “return” to return the variable. Example5 explains this concept where instead of displaying the result of the sum of the two variables; variable will be returned back to the calling function and displayed in the main method.

Example5
Code:

#include <iostream>
using namespace std;

int sum(int a, int b)  // Function Definition
{
        int result= a+b;
        return result;
}

int main()
{
        int num1, num2;
        cout<<"Enter the first number:";
        cin>> num1;

        cout<<"Enter the second number:";
        cin >> num2;
        int result = sum(num1,num2);
        cout <<"This sum of two numbers is: "<<result;

}

Look at Example5, in this example we have changed the return type of the sum function to int which means that the function will return the int function. Now inside the function body we have to use return statement and return some integer, if no suitable result is available, you can return 0.

Inside the main function we have defined another variable named result, and we have assigned the function call to this integer, when the function call executes the integer returned from the function call will be stored in the result variable in the main function. This result is then displayed in the main function which was previously done in the sum function. The output will be same.

Output5

http://imgs.g4estatic.com/functions-cpp/output5.png

Passing variable by reference



In all of the previous examples, we have passed variable to the function by value. Passing variable by value means that when variables are passed to the function. The function which has been called will create a copy of the variables and will store the arguments being passed in those variables. The original values in the calling function are not harmed.

Calling function by reference means that instead of passing actual values or variable, we pass the reference of those variables. References are basically memory addresses. When references are passed, the function being called do not create copy of variable, instead it directly manipulates the values stored in the reference, therefore the original values in the calling function are also changed once they are changed in the body of the function being called. This concept has been explained by

Example6.
Code:

#include <iostream>
using namespace std;


void reffunc(int & num)
{
    num=100;
}

int main()
{
        int number =50;
        cout <<"Value before function is called by reference:" <<number<<"\n";
        reffunc(number);
        cout <<"Value after function is called by reference:"<<number;
}

In Example6, we have a function named reffunc(int & num).

Pay attention to the parameter type in the parentheses, here you can see that we have used an ampersand, followed by the variable type. This is how you define a parameter which accepts reference from the calling function instead of a value.

Now come inside the main function, we have an integer variable number which has been initialized with value 10. We have passed this variable by reference to the reffunc(int & num) function. Inside the function we have changed its value to 20 and the function did not return anything.

Now after passing the variable by reference we will again print the number in the main function and we can see that its value has been changed to 20, since the called function altered the value.

The output of the function is

Output6

http://imgs.g4estatic.com/functions-cpp/output6.png

Function is an extremely vast concept and embodies lots of advanced features such as overloaded functions, overriding functions, virtual functions, static functions and so on. These concepts are beyond the scope of this tutorial and will be explained in any future tutorial in functions. Function also play a vital role in object oriented programming which we will see in our future tutorials.


All times are GMT +5.5. The time now is 17:17.