C – Pointers and Functions

After reading this pointers and functions topic, you will understand its theory and examples also you will know how to pass pointers to the functions.

In C Pointers and Functions, the Pointer as argument passes to the function. Two ways used to pass pointers to the functions are:

  • Call by value
  • Call by reference

Call by value:

When a value of variable as argument passes to the function and this type of passing arguments to function is known as call by value. The example below will show how call by value used in C programming.

#include<stdio.h>
#include<conio.h>
void main(void)
{
int a=10,b=20;
void swap(int,int);
printf("a=%d, b=%d",a,b);
swap(a,b);
getch();
}
void swap(int x,int y)
{
int t;
//swapping logic
t=x;
x=y;
y=t;
printf("\nx=a=%d, y=b=%d",x,y);
}

Output (1)

a=10, b=20
x=a=20, y=b=10

Call by reference:

When the address of memory location as argument passes to function and this type of passing arguments to function, known as call by reference. The call by reference also referred as passing address to function. The example below will show how call by reference used in C programming.

#include<stdio.h>
#include<conio.h>
void main(void)
{
int a=10,b=20;
void swap(int *,int* );
printf("a=%d, b=%d",a,b);
swap(&a,&b);
printf("\na=%d, b=%d",a,b);
getch();
}
void swap(int *x,int *y)
{
int t;
//swapping logic
t=*x;
*x=*y;
*y=t;
}

Output (1)

a=10, b=20
a=20, b=10

Published by

Electrical Workbook

We provide tutoring in Electrical Engineering.

Leave a Reply

Your email address will not be published. Required fields are marked *