- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is pass by reference in C language?
Pass by reference in C programming language is the addresses which are sent as arguments.
Algorithm
An algorithm is given below to explain the working of pass by value in C language.
START Step 1: Declare a function with pointer variables that to be called. Step 2: Declare variables a,b. Step 3: Enter two variables a,b at runtime. Step 4: Calling function with pass by reference. jump to step 6 Step 5: Print the result values a,b. Step 6: Called function swap having address as arguments. i. Declare temp variable ii. Temp=*a iii. *a=*b iv. *b=temp STOP
Example program
Following is the C program to swap two numbers using pass by reference −
#include<stdio.h> void main(){ void swap(int *,int *); int a,b; printf("enter 2 numbers"); scanf("%d%d",&a,&b); printf("Before swapping a=%d b=%d",a,b); swap(&a, &b); printf("after swapping a=%d, b=%d",a,b); } void swap(int *a,int *b){ int t; t=*a; *a=*b; // *a = (*a + *b) – (*b = * a); *b=t; }
Output
When the above program is executed, it produces the following result −
enter 2 numbers 10 20 Before swapping a=10 b=20 After swapping a=20 b=10
Let’s take another example to know more about pass by reference.
Example
Following is the C program to increment value by 5 for every call by using call by reference or pass by reference.
#include <stdio.h> void inc(int *num){ //increment is done //on the address where value of num is stored. *num = *num+5; // return(*num); } int main(){ int a=20,b=30,c=40; // passing the address of variable a,b,c inc(&a); inc(&b); inc(&c); printf("Value of a is: %d
", a); printf("Value of b is: %d
", b); printf("Value of c is: %d
", c); return 0; }
Output
When the above program is executed, it produces the following result −
Value of a is: 25 Value of b is: 35 Value of c is: 45
Advertisements