Sergei G
Sergei G

Reputation: 1570

Return pointer to a const array in c++

I have to 2 constant arrays in header files, say

const TPair<char, char> array1[] =
{
    {'V', rV},      
    {'v', rv},
    {'H', rH},
    {'h', rg},
    {0, 0}
};

and array2 similar to array1.
Now I need a function that will choose one of these arrays and return pointer to appropriate array.
How should signature of this function look like? And what do I return: array1 or array1&?

Upvotes: 1

Views: 2321

Answers (4)

James Kanze
James Kanze

Reputation: 154027

This a bit tricky. To start with, you don't want to put the definition of the array in the header. This results in an instance of the array in every translation unit which includes the header, most of which will never be used. And I'd definitly use a typedef. If the only way you access this array is through the return value of the function you ask about, then all you need in the header is a declaration for the function:

typedef TPair <char, char> CharPairArray[3];
CharPairArray const& getArray( bool condition );

(Without the typedef, the function declaration is:

TPair <char, char> const (&getArray( bool condition ))[3];

This is a route you don't want to go.)

If you also need to access the arrays otherwise, you need to add:

extern CharPairArray const array1;
extern CharPairArray const array2;

Then, is some source file (only one), you define the functions and the arrays:

CharPairArray const array1 = { /* ... */ };
CharPairArray const array2 = { /* ... */ };

CharPairArray const&
getArray( bool condition )
{
    return condition ? array1 : array2;
}

If you don't use the extern in the header, you can put the actual arrays in an unnamed namespace.

Upvotes: 3

johnsyweb
johnsyweb

Reputation: 141928

typedefs make this kind of code much more readable:

typedef TPair<char, char> pair_of_chars;

Then, ...

const pair_of_chars array1[] =
{
    // [...]
};

Your choosing function may look a bit like this:

const pair_of_chars* choose(int number)
{
    if (number == 1)
    {
        return array1;
    }
    return array2;
}

Upvotes: 3

Frunsi
Frunsi

Reputation: 7157

Like this:

const TPair<char,char>* choose() {
    return condition ? array1 : array2;
}

Upvotes: 2

Jarryd
Jarryd

Reputation: 1322

Its type should be:

const TPair<char, char>*

and you should return

array1

Upvotes: 2

Related Questions