16

I used C before (embedded stuff), and I can initialize my arrays like that:

int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };

i.e. I can specify indexes inside initializer. Currently I'm learning Qt/C++, and I can't believe this isn't supported in C++.

I have this option: -std=gnu++0x, but anyway it isn't supported. (I don't know if it is supported in C++11, because Qt works buggy with gcc 4.7.x)

So, is it really not supported in C++? Or maybe there's a way to enable it?

UPD: currently I want to initialize const array, so std::fill won't work.

13
  • 1
    "Or maybe there's a way to enable it?" - use C? (:D) Good question, +1. Commented Nov 26, 2012 at 10:30
  • 4
    Your code is neither C (including C11). C11 does not support initializing ranges this way ([a...b]=1), only single elements ([a]=1). Commented Nov 26, 2012 at 10:33
  • hmm... can you use extern "C" { ................ } around declaration? But I believe this syntax is your embedded compiler's addition. Commented Nov 26, 2012 at 10:33
  • 2
    @anishsane "I believe this syntax is your embedded compiler's addition" - no, it's a GNU extension to C99. Commented Nov 26, 2012 at 10:38
  • 2
    @ybungalobill Again, this is a GNU extension. Commented Nov 26, 2012 at 10:38

3 Answers 3

7

hm, you should use std::fill_n() for that task...

as stated here http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html the designated inits (extention) are not implemented in GNU C++

edit: taken from here: initialize a const array in a class initializer in C++

as a comment said, you can use std:vector to get the result desired. You could still enforce the const another way around and use fill_n.

int* a = new int[N];
// fill a

class C {
  const std::vector<int> v;
public:
  C():v(a, a+N) {}
};
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. Actually, I need to initialize const array, so, std::fill_n() won't work for me.
@DmitryFrank: Use std::vector, write a function that initializes the vector using fill_n and returns the result. Use this function to initialize a const vector.
You need delete a; also. Two dynamic allocation for filling array, isn't it an overkill?
After years, it works in g++ 4.8.2. :) when compiling with -std=c++11
4

After years, I tested it just by chance, and I can confirm that it works in g++ -std=c++11, g++ version is 4.8.2.

Comments

2

No, it is not possible to do it in C++ like that. But you can use std::fill algorithm to assign the values:

int widths[101];
fill(widths, widths+10, 1);
fill(widths+10, widths+100, 2);
fill(widths+100, widths+101, 3);

It is not as elegant, but it works.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.