Friday, 24 May 2013

Functions using Pointers

There are various ways to create or call a function using pointers. Here we will discuss few of them. We generally know there are ways of calling a function:
  1. Call by reference, and
  2. Call by value
With the help of the examples I'll let you know what does the above means. First of all let me tell you various ways of creating a new function:

1.   Function without using pointer:
void main ( )
{
        int a=5; 
        int b=6;
        int c;
        c= sum(a,b);
        printf("%d",c);
}
int sum(int a, int b)//Here a and b are dummy variables consisting of the values of a and b from above in different address
{
        return (a+b);
}

In the above code we are seeing a yellow marked command which is called as function calling as it is calling a function 'sum' with parameters 'a' and 'b'. The function 'sum' is defined in a green mark in which we are adding the values of 'a' and 'b' and passing these values in the main() function.
NOTE: The address of variables 'a' and 'b' in the main function is different from the address of the parameters of the 'sum' function. It means both variables are independent of each other.

The value is added in the 'sum' func and returned to main() function, by using return command, in 'c' variable and printing there only. 

2.   Function using Pointers (* and & both):

void main ( )
{
         int a=5,b=6,c;
         c= sum(&a1 , &b1);// here a and b passes the address to the func sum.
         printf("%d",c);
}
int sum(int *a, int *b)//pointers a and b stored with the address of a1 and b1 and pointing towards their value
{
         return (*a+*b);
}

Here we are using pointers in the parameters of the function because pointers points towards the value stored in the address which is stored in the pointer variable. The operation is similar to that of the above but the thing is way of representing it.

3.   Function using Pointers (& only):

void main ( )
{
         int a=5,b=6,c;
         c= sum(&a1 , &b1);
         printf("%d",c);
}
int sum (int &a1 , int &b1) //a1 and b1 points to the address of a and b in main func
{
         return (a1+b1);
}

4.   Function using Pointers (& once):

Call by Reference:

void main ( )
{
         int a=5,b=6,c;
         sum(a , b, c);
         printf("%d",c);
}
int sum(int a, int b, int &c)
{
         c= a+b;
}

Here &c refers c from main( ) function and stores the value in the same address without creating a new allocation for the value. This is called call by reference.

5.   Function using Pointer:

void main ( )
{
         int a=5,b=6,c;
         sum(a , b, &c);
         printf("%d",c);
}
int sum(int a, int b, int *c)
{
         *c= a+b;
}

Here int *c, parameter of sum func, is a pointer and it points towards the address of the c variable defined in the main.










No comments:

Post a Comment