Skip to main content

Functions and parameters

Functions

All most all programming language have a construct called procedure or function. A function is an independent unit of program which executes a particular task.


A C++ program is a group of functions. A function lives in its own stack – variables defined in a function are invisible to other functions.


To communicate with other functions, values are supplied to a function which are called parameters. A function can have 0 or more parameters of different types.


A function can send back one value to the caller function. This is called return value of the function. The type of this return value is called type of function.


Now let us look at syntax of a function


ret-type function-name(type par1,type par2, type par3)
{
......
body-of-function;
......
}
As shown above the function can have multiple parameters. Each of these must be defined with their type followed by name.

A function must have a unique name. Function name, parameter names and local variables defined within the function must all be valid unique identifiers.



Let us look at some example functions.

In the above example the function name is sum. It has two integer parameters a and b. And the function returns an integer – hence its type is integer.

The variable s declared inside function is visible only within the function. Even a and b are also only visible within the function.

We see how the function is called in main(). p and q which are sent to function are called arguments. They are copied to a and b. The value of function call is return value. And this is displayed using cout.

void function

A function may not return anything. Such a function can be defined as void function. 

void print_number(int num)
{
     cout<<num;
}

A void function can still use a return statement if necessary. But this return will be empty return.

void print_number(int num)
{
     if(num==0)
        return;
     cout<<num;
}
We are printing only non-zero numbers. So if the number is 0, we just terminate function.

A return statement terminates the function and returns a value to the caller. 

Call by Value and Call by Reference?

A function in C++ receives its parameters as a copy of original arguments. Parameters are stored in different locations than actual arguments so that the original values are unaffected after the function call. Any (one) value which needs to be sent back to caller, must be sent using return statement.

Let us look at an example.
#inlcude<iostream>
using namespace std;
void print_num(int a)
{
    a++;
    cout<<"a in print_num function is "<<a;
}
int main()
{
   int a = 12;
   print_num(a);
   cout<<"Now a in main is "<<a;
}

Now let us look at the output

a in print_num function is 13
Now a in main is 12

So a in print_num function is a different variable than a in main function. It does not matter whether you give the same name to parameter as that of argument or a different name. Even though in print_num  a is incremented, the original value of a in main remains same.

Return multiple values from function

Some times a function needs to return more than one value. How do we do that? Use 2 return statements in function?

No, that does not work. Because first return will terminate function and second return is never executed.

The solution is to use pointers or references as parameters. Let us look at both the methods.

#include<iostream>
using namespace std;
void swap(int *ptra, int *ptrb)
{
   int temp = *ptra;
   *ptra = *ptrb;
   *ptrb = temp;
}
int main()
{
   int a=10,b=12;
   swap(&a,&b);
   cout<<"Now a is"<<a<<" b is "<<b<<endl;
}

Here two parameters to swap function are pointers to integers. And we send address of a and address of b as arguments. ptra has address of a and *ptra indirectly accesses a. So change to *ptra changes a. And change to *ptrb modifies b.

So the output is
Now a is 12 b is 10

But using pointer parameter is risky. We may crash the program if the pointer is not initialized or is NULL.

The second solution is using references. Let us rewrite swap function using reference parameters.

#include<iostream>
using namespace std;
void swap(int &refa, int &refb)
{
   int temp =  refa;
   refa= refb;
   refb = temp;
}
int main()
{
   int a=10,b=12;
   swap( a, b);
   cout<<"Now a is"<<a<<" b is "<<b<<endl;
}

 swap function now takes two reference parameters - (int &). refa is an alias for a and refb is an alias for b. So when refa and refb are swapped in swap function, a and b are also changed in main. So

A reference parameter looks like a ordinary parameter, but behaves like a pointer parameter. 

Assign a value to function?

No, I am not joking! You can in fact assign a value to function call - if the function returns a reference value.

Let us look at an example


#include<iostream>
using namespace std;
int & foo(int &a,int &b)
{
    if(a>b)
      return a;
    return b;
}
int main()
{
   int p,q;
   cin>>p>>q;
   foo(p,q)=0;
   cout<<"p is "<<p<<" q is "<<q<<endl;
}
the function foo() returns a reference to an integer - its return type is int&. In fact it returns a reference to the parameter which is larger.

In main foo(p,q)=0  assigns 0 to the return value of the function. That is to say that the statement assigns 0 to the returned reference value.

So what will be the output of the program?

We clearly see that after the function call, larger of p and q is assigned to 0.

A weird way of computing? But some times you do need to assign a value to return value of a function. You see the application of this method in overloading subscript operator ([]) of an array object.

That is not the end of this discussion. C++ has some more new features like overloaded functions and default arguments. We will see them in next post.



Comments

Popular posts from this blog

Find the error in C++ program

This C++ program is not compiling. What do you think is the error with the program? #include<iostream> using namespace std; int main() {    int arr[10];    arr={1,2,3,4,5,6,7,8};    cout<<"arr[0]="<<arr[0];    return 0; } Is the error due to Not using printf Initialising the array with only 8 elements instead of 10 Initialising array in the next statement instead of in definition. None of the above  Now if you like this question, there are plenty more questions like this and programs and notes in my app Simplified C++. Download the Simplif ied C++   by Hegdeapps now By the way the correct answer is (3)

Abstract class

 If we can not create any objects of a class, then it is called an abstract class. A class is made abstract by adding at least one pure virtual function to it. Pure virtual function A function is said to be a pure virtual function , if it has no definition but has only declaration. Pure virtual function is defined with the keyword virtual and followed by return type, function name and "=0". class Shape { public: virtual void printarea() =0 ; }; int main () { Shape obj1; //error } Here printarea() function of Shape class is a pure virtual function as it has no body. To make a function as pure virtual function, you should use =0 at the end of virtual function declaration Abstract class When a class has at least one pure virtual function, it is incomplete and no objects can be created from that class. Such a class is called an abstract class . In the earlier example class Shape is an abstract class, and objects can not be created from t...

Friends of C++

Friend function Remember that a member which is not public (Private and protected )  can not be accessed from outside the class.  Three are some situations where you may need to access these. Keyword friend  is used for this. A friend functions and classes can access all members of a class.  This concept is controversial. People say friend concept violates data encapsulation  A friend function is a non-member function but still can access all the members of a class including private members. Such a function is declared within class body with the prefix "friend" class Number { int num; public: Number( int m){ /*code*/ } friend void printNum(Number ob); /*friend function*/ }; void printNum (Number obj) { cout << obj.num << "endl" ; } printNum() is not member of class Number . But it can still access all members including private members, because it is a friend. Friend class An object of a friend c...