Wednesday, July 09, 2008

Pointers and function in C programming language

The pointer is very much used in a function declaration. Sometimes only with a pointer a complex function can be simply represented and success. The usage of the pointers in a function definition possibly will be categorized into two groups.
1. Call by reference
2. Call by value.

Call by value

We have seen that a function is called there will be a link established between the formal and actual parameters. A temporary storage space is created where the value of actual parameters is stored. The formal parameters picks up its value from storage space area the method of data transfer relating actual and formal parameters allows the actual parameters mechanism of data transfer is referred as call by value. The corresponding formal parameter represents a local variable in the called function. The current value of matching actual parameter becomes the initial value of formal parameter. The value of formal parameter can be changed in the body of the actual parameter. The value of formal parameter can be changed in the body of the subprogram by task or input statements. This will not change the value of actual parameters.

/* Include<>
void main()
{
int x,y;
x=20;
y=30;
printf(“\n Value of a and b before function call =%d %d”,a,b);
fncn(x,y);
printf(“\n Value of a and b after function call =%d %d”,a,b);
}

fncn(p,q)
int p,q;
{
p=p+p;
q=q+q;
}

Call by Reference

The process of calling a function by using pointers to pass the address of the variable is known as call by reference. The function which is called by reference can change the values of the variable used in the call.

/* example of call by reference*?

/* Include<>
void main()
{
int x,y;
x=20;
y=30;
printf(“\n Value of a and b before function call =%d %d”,a,b);
fncn(&x,&y);
printf(“\n Value of a and b after function call =%d %d”,a,b);
}

fncn(p,q)
int p,q;
{
*p=*p+*p;
*q=*q+*q;
}

No comments: