0
$\begingroup$

Given the following code: int p = 5 , q=2; int f( int b, int c){ b = 2 * c; c = 3 + p; return b + c ;} print f(p,q); print p; print q;

I have found that the output values using call by value are: f(p,q)=12 p=5 q=2

And as far as i know also the output using call by reference in this example ,gives the same values.Am I right?

$\endgroup$

1 Answer 1

0
$\begingroup$

Both by value:

{p = 5, q = 2, b = 5, c = 2}
b= 2 * c; 
{p = 5, q = 2, b = 4, c = 2} 
c= 3 + p; 
{p = 5, q = 2, b = 4, c = 8}
return b + c;
{b + c = 12}

Both by reference:

{p = b = 5, q = c = 2}
b= 2 * c; 
{p = b = 4, q = c = 2}
c= 3 + p; 
{p = b = 4, q = c = 7}
return b + c;
{b + c = 11}
$\endgroup$
2
  • $\begingroup$ Thank you very much ,its very helpful. $\endgroup$
    – yaman
    Apr 1 at 10:48
  • $\begingroup$ int n = 3; int m = 9; public void f(int x, int y){ int n = 5; x = n; m = y - 2; } public static void main(String[] args){ f(m, n); System.out.println(n); System.out.println(m); } I have found that the output value using call by value are 3 and 1 and using call by reference the values are 5 an 1. Am i right? $\endgroup$
    – yaman
    Apr 1 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.