-3

I have the following C-like program, and I'm trying to figure out the final value of array x for when:

  • Argument x is passed by value.
  • Argument x is passed by reference.
  • Argument x is passed by value-result.

CODE:

void swap(int[] list, int i, int j)
{
    int temp = list[i];
    list[i] = list[j];
    list[j] = temp;
}

void main() 
{
    int x[3] = {5, 2, 4};
    swap(x, 1, 2);
}

If I'm following correctly, for pass by value, in the call we have...

swap(x, 1, 2)
{
    temp = x[1] // temp now equals 2
    x[1] = x[2] // x[1] now equals 4
    x[2] = temp // x[2] now equals 2
}

...so then we have the following, correct?

x[3] == {5, 4, 2}

EDIT:

I tried compiling on ideone.com and received:

prog.c:1:17: error: expected ‘;’, ‘,’ or ‘)’ before ‘list’
 void swap(int[] list, int i, int j)
                 ^
prog.c:8:6: warning: return type of ‘main’ is not ‘int’ [-Wmain]
 void main() 
      ^
prog.c: In function ‘main’:
prog.c:11:5: warning: implicit declaration of function ‘swap’ [-Wimplicit-function-declaration]
     swap(x, 1, 2);
     ^
Analytic Lunatic
  • 3,853
  • 22
  • 78
  • 120
  • 6
    The programming language only passes values by value – Ed Heal Dec 11 '13 at 23:56
  • `int[] list` equals to `int* list` so you're always passing pointer to first element of array to this function (not value, not reference, but pointer or value of pointer if you like) – Iłya Bursov Dec 11 '13 at 23:57
  • If you were passing `x` by value, `swap` wouldn't be altering the `x` in `main`, so it wouldn't do anything from main's POV. (I'm assuming some "C like" language where you can actually pass an array by value) – Blorgbeard Dec 11 '13 at 23:57
  • 4
    What do you mean by "C-like"? In actual C, the array would be effectively passed by reference here, not by value. When you pass an array like this C actually passes a pointer to the array's first member, not the array itself. – John Kugelman Dec 11 '13 at 23:58
  • 1
    The easiest way to figure out the answer is to run the code. – Dwayne Towell Dec 12 '13 at 00:14

1 Answers1

1

Actually, when you call

swap(x, 1, 2);

you are using call-by reference, since you are passing the argument x, which is a pointer to the first element of the array x. So this swap technique will work and you will get what you are expecting, that the elements will now be in the order {5,4,2}

SoulRayder
  • 5,072
  • 6
  • 47
  • 93
  • I see. So then what about pass by `VALUE` and `VALUE-RESULT`? Any thoughts on those? – Analytic Lunatic Dec 12 '13 at 15:08
  • I don't think pass by value will be useful in your scenario, since it only works on *copies* of variables rather than on the variables themselves. In any case, here is a link so that you can decide for yourself: http://courses.cs.washington.edu/courses/cse505/99au/imperative/parameters.html – SoulRayder Dec 13 '13 at 04:36