2

I have an array declared in my header file like this:

int snapshot[kSnapshotSize];

which I would really love to init like this in my implementation file:

snapshot[kSnapshotSize] = {[0 ... kSnapshotSize-1] = 5};

however the compiler complains: "Expected expression"

Can anyone tell me what I'm doing wrong?

UPDATE: int snapshot[kSnapshotSize] = {[0 ... kSnapshotSize] = 5}; seems to work, so probably I'm missing something basic. I think I can use memset, but would first want to be sure this is not possible (and why)

UPDATE 2: As many of you pointed out, it seems that it's only possible to init an array like that not to populate it later. I end up using a for loop.

2
  • 1
    You can't use the initializer outside an initialization for the same reason you can't do array assignments in general. It is interesting to know that there is the GNU (GCC) extension to C99 designated initializers to support initializing ranges in an array. That is something that Fortran allows - and always struck me as 'something missing' from the otherwise extremely useful C99 designated initializer syntax. Commented Oct 15, 2011 at 20:43
  • yeah, initializing ranges in an array is pretty handy, to bad you can only use it on init. Anyway, I'm sure there is a reason for that. Commented Oct 15, 2011 at 20:56

1 Answer 1

6

I presume you mean

int snapshot[kSnapshotSize] = {[0 ... kSnapshotSize - 1] = 5};

But that use of ... is a gcc-specific extension. If you don't mind being limited to gcc, that's ok.

memset() won't work; it sets each byte of the target to the specified value.

For portability, your best bet is to use an explicit loop to set each element.

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

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.