Thursday, January 20, 2011

15.Passing Arguments to Function


In order to write correct function you should know how to pass arguments to it. C supports a wide range of mechanisms to allow you to program functions effectively.

Pass by value

With this mechanism, all arguments you pass to function are copied into copy versions and your function work in that copy versions. So parameters does not affects after the function finished.

Pass by pointer

In some programming contexts, you want to change arguments you pass to function. In this case, you can use pass by pointer mechanism. Remember that a pointer is a memory address of a variable. So when you pass a pointer to a function, the function makes a copy of it and changes the content of that memory address, after function finish the parameter is changed with the changes in function body.

Pass an array to function

C allows you pass an array to a function, in this case the array is not copied. The name of array is a pointer which points to the first entry of it. And this pointer is passed to the function when you pass an array to a function.


#include<stdio.h>

/* functions declaration */

/* demonstrate pass by pointer */
void swap(int *x, int *y);

/* demonstrate pass by value */
void swap(int x, int y);

/* demonstrate pass an array to the function */
void bubble_sort(int a[], int size);

void print_array(int a[],int size);

void main()
{
int x = 10;
int y = 20;


printf("x,y before swapping\n");
printf("x = %d\n",x);
printf("y = %d\n",y);

// pass by value
swap(x,y);

printf("x,y after swapping using pass by value\n");
printf("x = %d\n",x);
printf("y = %d\n",y);

// pass by pointer
swap(&x,&y);

printf("x,y after swapping using pass by pointer\n");
printf("x = %d\n",x);
printf("y = %d\n",y);

// declare an array
const int size = 5;
int a[size] = {1,3,2,5,4};

printf("array before sorting\n");
print_array(a,size);

bubble_sort(a,size);

printf("array after sorting\n");
print_array(a,size);


}


/* functions implementation */

void swap(int *x, int *y){
int temp = *x;
*x = *y;
*y = temp;
}

void swap(int x, int y){
int temp = x;
x = y;
y = temp;
}

void bubble_sort(int a[], int size)
{
int i,j;
for(i=0;i<(size-1);i++)
for(j=0;j<(size-(i+1));j++)
if(a[j] > a[j+1])
swap(&a[j],&a[j+1]);
}

void print_array(int a[],int size)
{

for(int i = 0;i < size; i++)
{
printf("%d\t",a[i]);
printf("\n");
}
}


Here is the output

x,y before swapping
x = 10
y = 20
x,y after swapping using pass by value
x = 10
y = 20
x,y after swapping using pass by pointer
x = 20
y = 10
array before sorting
1
3
2
5
4
array after sorting
1
2
3
4
5

Dont Miss Another Post Connect With Us !

Enter your email address:

0 comments: