user1403588
user1403588

Reputation: 804

Return pointer to array or make void function with parameter

Till now most of the time I was using functions that return pointer to array, but now I started using void function with reference to array, so I am wondering which one of below code is better to use and why?

void doSomething(int** &ary)
{
    ary = new int*[3];
    for (int i = 0; i < 3; ++i)
        ary[i] = new int[3];
    ary[0][0] = 1;
    ary[0][1] = 2;
}

int** ary=NULL;
doSomething(ary);

or this

int** doSomething1()
{
    int **ary = new int*[3];
    for (int i = 0; i < 3; ++i)
        ary[i] = new int[3];
    ary[0][0] = 1;
    ary[0][1] = 2;
    return ary;
}

int **ary1=doSomething1();

Upvotes: 2

Views: 343

Answers (2)

user4281841
user4281841

Reputation: 11

There is no big difference between the two examples, however I'd prefer the second example.

In the first example, you take a reference to ary, which means your program has to dereference all pointers each time it accesses an element somewhere in ary. (A reference is equivalent to a pointer after the code has been compiled)

In the second example, you only need to copy the pointer when the function returns.

First example:

reference to pointer to array -> pointer to array -> element in array

Second example:

pointer to array -> element in array

Upvotes: 0

This is a question of opinion, however, here is mine:

I think the version that returns the pointer is better. Why? Simply because it makes the calling site less magic. With the return variant, you call the function like this:

int** my2dArray = doSomething();

It is perfectly clear, that my2dArray is initialized to point to some array that the function supplies. Without a single look at the function definition.

On the other hand, the call

int** my2dArray;
doSomething(my2dArray);

should always ring an alarm bell for the reader: It looks as if you are passing an uninitialized pointer to the function. Even after looking up the function definition, and seeing that the pointer is passed by reference, a reader still can't be certain that the function does not interpret the value that is passed in. It requires a close look at the code to make sure that this call is indeed legitimate.

So, for the sake of debugability, I avoid passing reference arguments. I pass by value, I pass by const reference (which has the same semantic as pass by value), or I pass by explicit pointer. That way no function call can modify a value that is not explicitly visible at the calling site.

Upvotes: 1

Related Questions