InterviewSolution
| 1. |
What is the difference between call by value and call by reference? |
||||||||
|
Answer» Let us first take a look at the definitions of Call by Value and Call by Reference before taking a look at the differences between the two:
Let us now take a look at the differences between Call by Value and Call by Reference in detail:
An example each to illustrate the difference between Call by Value and Call by Reference in C is given below: Call by Value Example: // Illustrating call by value in C#INCLUDE <stdio.h>// Prototype of the function "addNumbers"void addNumbers(int a, int b);// The main function of the C programint main(){ int X = 50, y = 30; // Passing x and y by Values addNumbers(x, y); printf("x = %d y = %d\n", x, y); return 0;}// Function to add two Numbers and stores the result in the first number passedvoid addNumbers(int a, int b){ a = a + b; printf("a = %d b = %d\n", a, b);}Output: a = 80 b = 30a = 50 b = 30
Call by Reference Example: // Illustrating call by value in C#include <stdio.h>// Prototype of the function "addNumbers"void addNumbers(int *a, int *b);// The main function of the C programint main(){ int x = 50, y = 30; // Passing x and y by Values addNumbers(&x, &y); printf("x = %d y = %d\n", x, y); return 0;}// Function to add two Numbers and stores the result in the first number passedvoid addNumbers(int *a, int *b){ *a = *a + *b; printf("a = %d b = %d\n", a, b);}Output: a = 80 b = 30a = 80 b = 30
|
|||||||||