Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way of passing array parameters to D functions

Tags:

arrays

d

1st Question:

Are D array function parameters always passed by reference, or by value? Also, does the language implements Copy on Write for arrays? E.g.:

void foo(int[] arr)
{
    // is arr a local copy or a ref to an external array?

    arr[0] = 42; // How about now?
}

2nd Question:

Suppose I have a large array that will be passed to function foo as a read-only parameter and it should be avoided as much as possible copying the array, since it is assumed to be a very large object. Which from the following (or none of them) would be the best declaration for function foo:

void foo(const int[] bigArray)

void foo(in int[] bigArray)

void foo(const ref int[] bigArray)
like image 990
glampert Avatar asked Jun 08 '14 02:06

glampert


People also ask

How do you pass an array as a parameter to a function?

To pass an array as a parameter to a function, pass it as a pointer (since it is a pointer). For example, the following procedure sets the first n cells of array A to 0. Now to use that procedure: int B[100]; zero(B, 100);

What are two ways to pass array to a function?

There are two possible ways to do so, one by using call by value and other by using call by reference.

When you pass an array to a function the function receives?

An array passed to a function decays into a pointer to its first element.


1 Answers

  1. Technically, a dynamic array like int[] is just a pointer and a length. Only the pointer and length get copied onto the stack, not the array contents. An arr[0] = 42; does modify the original array.
    On the other side, a static array like int[30] is a plain old data type consisting of 30 consecutive ints in memory. So, a function like void foo(int[30] arr) would copy 120 bytes onto the stack for a start. In such a case, arr[0] = 42; modifies the local copy of the array.

  2. According to the above, each of the ways you listed avoids copying the array contents. So, whether you need the parameter to be const, in, const ref or otherwise depends on what you are trying to achieve besides avoiding array copy. For example, if you pass a ref int [] arr parameter, not only you can modify its contents, but also you will be able to modify the pointer and length (for example, create a wholly new array and assign it to arr so that it is visible from outside the function).

For further information, please refer to the corresponding articles on the DLang site covering arrays and array slices.

like image 107
Gassa Avatar answered Sep 21 '22 04:09

Gassa