1

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&?

4 Answers 4

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

Its type should be:

const TPair<char, char>*

and you should return

array1

Comments

2

Like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.