- 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 value in C language?
Pass by value is termed as the values which are sent as arguments in C programming language.
Algorithm
An algorithm is given below to explain the working of pass by value in C language.
START Step 1: Declare a function that to be called. Step 2: Declare variables. Step 3: Enter two variables a,b at runtime. Step 4: calling function jump to step 6. Step 5: Print the result values a,b. Step 6: Called function swap. i. Declare temp variable ii. Temp=a iii. a=b iv. b=temp STOP
Example
Given below is the C program to swap the two numbers by using pass by value −
#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; // all these statements is equivalent to t=a; // a = (a+b) – (b =a); a=b; // or b=t; // a = a + b; } // b = a – b; //a = a – b;
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=10 b=20
Let’s take another example to know more about pass by value.
Example
Following is the C program to increment value by 5 for every call by using call by value or pass by value −
#include <stdio.h> int inc(int num){ num = num+5; return num; } int main(){ int a=10,b,c,d; b =inc(a); //call by value c=inc(b); //call by value d=inc(c); //call by value printf("a value is: %d
", a); printf("b value is: %d
", b); printf("c value is: %d
", c); printf("d value is: %d
", d); return 0; }
Output
When the above program is executed, it produces the following result −
a value is: 10 b value is: 15 c value is: 20 d value is: 25
Advertisements