8

I am initializing an array in two different ways depending a macro:

# if feature_enabled
const int v[4] = {1, 2, 3, 4};
#else
const int v[5] = {0, 1, 2, 3, 4};
#endif

The problem is that the data in the assignment is actually large matrices, and for various reasons it's not a good solution to just copy the data with a minor modification (just one more element at the beginning of the array.)

I was wondering if there is a way to do the same thing that I did here, without essentially duplicating the last n-1 elements.

5
  • 6
    Do you know that the array size does not match the number of elements in the initializer list? Commented Dec 6, 2019 at 14:17
  • @mch fixed it now, it was just something I typed up for the question. Commented Dec 6, 2019 at 14:31
  • @C.E. "and for various reasons it's not a good solution to just copy the data with a minor modification" - Could you give us a reference for that, what is your worry about? Commented Dec 6, 2019 at 17:05
  • @RobertS-ReinstateMonica Why, in general, is duplicating code bad? That's a rather broad topic. Luckily, I got my answer anyway. Commented Dec 6, 2019 at 18:13
  • @C.E. You do not need to make an over-detailed explanation, it were just be fine if you could give a reference at least to what you are pointing to and which is the base of that question. So, people who aren´t confirmed with these things can understand the purpose of that question. Commented Dec 6, 2019 at 18:20

2 Answers 2

16

If you don't specify the size on the array but let it be auto-deduced, you can just add the 0 in the front conditionally:

const int v[] = {
# if feature_enabled
  0,
#endif
  1, 2, 3, 4
};
Sign up to request clarification or add additional context in comments.

Comments

3

If you need to keep the array size, then:

# if feature_enabled
const int v[4] = {
#else
const int v[5] = {0,
#endif
  1, 2, 3, 4
};

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.