0% found this document useful (0 votes)
49 views

C Programming Pointers and Functions

This document discusses how pointers and functions can be used to swap two numbers by passing the addresses of the numbers (call by reference) rather than their values. It provides an example C program that defines a swap function that takes two integer pointers as arguments, swaps the integer values they point to by assigning one to a temporary variable and then assigning the other to the first pointer and the temporary back to the second pointer. This swaps the actual numbers in memory rather than just their local function values.

Uploaded by

slspa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

C Programming Pointers and Functions

This document discusses how pointers and functions can be used to swap two numbers by passing the addresses of the numbers (call by reference) rather than their values. It provides an example C program that defines a swap function that takes two integer pointers as arguments, swaps the integer values they point to by assigning one to a temporary variable and then assigning the other to the first pointer and the temporary back to the second pointer. This swaps the actual numbers in memory rather than just their local function values.

Uploaded by

slspa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

C Programming Pointers and Functions - Call

by Reference
When, argument is passed using pointer, address of the memory location is passed instead of value.

Example of Pointer And Functions


Program to swap two number using call by reference.
/* C Program to swap two numbers using pointers and function. */
#include <stdio.h>
void swap(int *a,int *b);
int main(){
int num1=5,num2=10;
swap(&num1,&num2); /* address of num1 and num2 is passed to swap function */
printf("Number1 = %d\n",num1);
printf("Number2 = %d",num2);
return 0;
}
void swap(int *a,int *b){ /* pointer a and b points to address of num1 and num2 respectively */
int temp;
temp=*a;
*a=*b;
*b=temp;
}

Output
Number1 = 10
Number2 = 5

Explanation
The address of memory location num1 and num2 are passed to function and the pointers *a and *b accept those
values. So, the pointer a and b points to address of num1 and num2 respectively. When, the value of pointer are
changed, the value in memory location also changed correspondingly. Hence, change made to *a and *b was
reflected in num1 and num2 in main function.
This technique is known as call by reference in C programming.

You might also like