0

This is essentially what I'm trying to do, but not the actual source code.

namespace namespace { int array [3]; } namespace::array={1,2,3}

my gcc asks for an expression, and I'm not sure of what to do. Must I namespace::array[1]; each individual element?

4 Answers 4

6

You can only use an initializer list in a definition:

int array[3] = { 1, 2, 3 };

If you use:

int array[3];

then you need to initialize the array in a function, using

array[0] = 1; 
array[1] = 2; 
array[2] = 3;
Sign up to request clarification or add additional context in comments.

Comments

3

Although it an odd mixture of C99 and C++, gcc allows this:

#include <string.h>
int a[3];

int main()
{
    memcpy(a, (int[3]){ 1, 2, 3}, sizeof(a));
}

!

2 Comments

..that is indeed odd, I've never seen anything like that before! +1 for uniqueness...
I checked the assembly and it does work. I suspect it would also work for non-constant expressions.
0

How about namespace ns { int array[3] = {1, 2, 3}; }?

Comments

0

There are several ways:

1) Explicitly set values for each element:

namespace ns {
    int array [3];
}
ns::array[0]=1;
ns::array[1]=2;
ns::array[2]=3;
\\ or if they should contain consequtive values:
\\ for (size_t i = 0; i < 3; ++i)
\\     ns::array[i] = i + 1;

2) If you want initialize static array in place of its declaration, then you could move it initializer list as follows:

namespace ns {
    int array[3] = {1, 2, 3};
}

3) Use typedef:

namespace ns {
    typedef int array_t[3];
}
ns::array_t array = {1, 2, 3};

3) Also you can make some research of std::tr1::array, which may be used as such:

std::tr1::array<int, 3> arr = {1, 2, 3};

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.