0
#include <iostream>

using namespace std;

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

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

I am trying to figure out what this means, I get the passed by value. However I am not too familiar with pointers and value-results? Will some one explain or point me to an example dealing with C and the methodologies below?

  1. Argument x is passed by value.
  2. Argument x is passed by reference.
  3. Argument x is passed by value-result.
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Purple_Rain
  • 79
  • 1
  • 7
  • 2
    C or C++? The answer is different for each. Passing by reference means "passing by reference type" in C++, while it means "using reference semantics" in C. – Joseph Mansfield Jul 02 '14 at 17:05
  • 1
    possible duplicate of [Pass by pointer & Pass by reference](http://stackoverflow.com/questions/8571078/pass-by-pointer-pass-by-reference) – Cory Kramer Jul 02 '14 at 17:05
  • You are passing a *pointer* to the first element of `x`. – juanchopanza Jul 02 '14 at 17:06
  • 3
    Did you know that `list` is a class in the `std` namespace? This is *one* reason to *not* use `using namespace std;`: it avoids confusion and potential errors in code. – crashmstr Jul 02 '14 at 17:07
  • This isn't C++. (Maybe C++/CLI, but that's still a different language.) – James Kanze Jul 02 '14 at 17:29
  • Your code shouldn't compile: `int[] list` should be `int list[]`, and `void main()` should be `int main()` – milleniumbug Jul 02 '14 at 17:44
  • possible duplicate of [What are the differences between pointer variable and reference variable in C++?](http://stackoverflow.com/questions/57483/what-are-the-differences-between-pointer-variable-and-reference-variable-in-c) – László Papp Jul 03 '14 at 00:12

2 Answers2

1

Your confusion is caused by the fact that arrays do not exist in function argument lists.

To elaborate:

void swap(int list[25], int i, int j)
void swap(int list[5], int i, int j)
void swap(int list[], int i, int j)
void swap(int* list, int i, int j)

are actually the same function.

Also:

int arr[30];
int* ptr = arr; // does the same as int* ptr = &arr[0]

These confusing semantics for C-style arrays was the reason why std::array was created.

And to answer your question:

  1. You can't pass C-array by value.
  2. You can pass C-array by reference (void fun(int (&arr)[3]) is a function that takes three-element array by reference)
  3. There is no pass by value-result in C++.

Check this Stack Overflow question for more details about arrays

Community
  • 1
  • 1
milleniumbug
  • 15,379
  • 3
  • 47
  • 71
0

[You should try this code on your codeblocks. i have explained all arguments in comment line to better understand.][1]

enter code here

https://ideone.com/17oQZV