2

In my answer to this question it was mentioned that the code I posted wouldn't work if the variable was declared as const.

What if i want to initialize a long array that's const type

int main (){
    const int ar[100];
 //this is invalid in c++
 //something like this

    for (int i=0;i <100;++i)
        ar[i]=i;
    return 0;
}

Are there other ways to do this than using the #define method proposed in that question?

16
  • Can you elaborate? I don't understand what you're asking Commented Jun 10, 2015 at 13:46
  • @CoryKramer I think he's saying that he can't modify a const int[] after definition, therefore he can't initialize it. Commented Jun 10, 2015 at 13:47
  • 1
    const int ar[100]; is not even legal C++, you cannot leave the array un-initialized Commented Jun 10, 2015 at 13:50
  • 1
    I suppose this is a follow-up question to my comment to this answer? In that case, simply check the answer posted by yours sincerely to that question. Commented Jun 10, 2015 at 13:57
  • 1
    There is no standard way to do so. Here is a very similar question with a very similar answer by me, plus some answers suggesting non-standard gcc extensions. Commented Jun 10, 2015 at 14:35

2 Answers 2

2

There's no way to do it directly, without hacks.

In C++ one way to work around this problem is to take advantage of the fact that inside their constructors const objects are still modifiable. So, you can wrap your array into a class and initialize it in the constructor

struct Arr 
{
  int a[100];

  A() 
  {
    for (unsigned i = 0; i < 100; ++i)
      a[i] = i;
  }
};

and then just declare

const Arr arr;

Of course, now you will have to access it as arr.a[i], unless you override the operators in Arr.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use a trick... initialize a regular array and then get a reference to a const array:

int arr[100];
for (int i=0; i<100; i++) arr[i] = i*i;

const int (&carr)[100] = arr;

1 Comment

Cool thats somewhag cheating lol.... nice way though

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.