Consider the following program written in C-like syntax: void incr(int first, int second) { first = first + 1; second = second + 1; } void main() { int a=3; b=5; incr(a,b) ; } For each of the following parameter-passing methods, what are the values of the vari- ables a and b after execution? Explain in detail. (a) call by value (b) call by reference (c) call by value-result

Respuesta :

Answer:

Check the explanation

Explanation:

By doing call by value parameter passing the values remain unchanged even after the function call as the values of actual parameters cannot be altered with the help of the formal parameters. Here is an example code of the above stated C syntax and it’s output clearly shows that there is no change in the values even after function incr is called.

Code in C:-

#include <stdio.h>

// function incrementing the values

void incr(int first, int second)

{   printf("\nBefore updation in the values\nfirst = %d second = %d",first,second);

   // incrementing the first and second values

   first = first + 1;

   second = second+ 1;

   printf("\nAfter updation in the values\nfirst = %d second = %d",first,second);

}

int main()

{   // Decalring the values of a and b

   int a=3, b=5;

   printf("\tCALL BY VALUE\n\n");

   printf("Before the function call\na = %d b = %d",a,b);

   // Value passing in the function incr

   incr(a,b);

   printf("\nAfter the function call\na = %d b = %d",a,b);

   return 0;

}

Kindly check the first and second attached image below for the code screenshot and code output.

By doing call by reference parameter passing the values change after the function call as the values of actual parameters can be altered with the help of the formal parameters. Values are passed as a reference in this case. Here is an example code of the above stated C syntax and it’s output clearly shows that there is change in the values after function incr is called.

Code in C:-

#include <stdio.h>

// function incrementing the values

void incr(int *first, int *second)

{   printf("\nBefore updation in the values\nfirst = %d second = %d",*first,*second);

   // incrementing the first and second values

   (*first)=(*first)+ 1;

   (*second)=(*second)+ 1;

   printf("\nAfter updation in the values\nfirst = %d second = %d",*first,*second);

}

int main()

{   // Decalring the values of a and b

   int a=3, b=5;

   printf("\tCALL BY REFERENCE\n\n");

   printf("Before the function call\na = %d b = %d",a,b);

   // Reference passing in the function incr

   incr(&a,&b);

   printf("\nAfter the function call\na = %d b = %d",a,b);

   return 0;

}

Kindly check the third and fourth attached image below for the code screenshot and code output.

Ver imagen temmydbrain
Ver imagen temmydbrain
Ver imagen temmydbrain
Ver imagen temmydbrain