| 1. |
Differentiate between Call by Value and Call by Reference. |
||||||||
|
Answer» Before we look at the key differences between the two, let us take a look at the definitions of Call by Value and Call by Reference:
Now, let us take a closer look at the distinctions between Call by Value and Call by Reference:
The following is an example of each to demonstrate the difference between Call by Value and Call by Reference in C: Coding Example of Call By Value: // Illustration of Calling VIA Value using C program#include <stdio.h>// Prototype of the function "subtract"void subtract(float c, float d);// The main function of the C codeint32_t main(){ float a = 71.0, b = 21.0; // Passing a and b and calling the subtract function by Value subtract(a, b); printf("a = %f b = %f\n", a, b); return 0;}// Method DEFINITION to subtract two NUMBERS and store the answer in the first number passedvoid subtract(float c, float d){ c = c - d; printf("c = %f d = %f\n", c, d);}Output: a = 50.0 b = 21.0 // Printed value in the subtract functiona = 71.0 b = 21.0 // Printed value in the main function
Coding Example of Call By Reference: // Illustration of Calling via Reference using C program#include <stdio.h>// Prototype of the function "subtract"void subtract(float *c, float *d);// The main function of the C codeint32_t main(){ float a = 71.0, b = 21.0; // Passing a and b and calling the subtract function by Reference subtract(&a, &b); printf("a = %f b = %f\n", a, b); return 0;}// Method definition to subtract two Numbers and store the answer in the first number passedvoid subtract(float *c, float *d){ *c = *c - *d; printf("c = %f d = %f\n", c, d);}Output: a = 50.0 b = 21.0 // Printed value in the subtract functiona = 50.0 b = 21.0 //. Printed value in the main function
|
|||||||||