1

I have an constant array like this:

const int foo[NUM] = {
    9000,
    4400,
    620,
    480,
    1620
};

How can I create another const array that will do some math operations on the variables from foo? I tried this:

const int bar[NUM] = {
    foo[0] / (DEFINE1* DEFINE2),
    foo[1] / (DEFINE1* DEFINE2),
    foo[2] / (DEFINE1* DEFINE2),
    foo[3] / (DEFINE1* DEFINE2),
    foo[4] / (DEFINE1* DEFINE2)
};

However this doesnt work, it returns errors:

Error 2 (near initialization for 'bar[0]'), for all elements

Error 1 initializer element is not constant, for all elements

2 Answers 2

5

C consts are not real constants, as described in this C FAQ. As such, the compiler only enforces that you can't write to them. For all other uses, they are not constants (the way your defines are).


Side note: this is one of the areas where C and C++ differ. In C++ const has a markedly different meaning, closer to what you are trying.

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

3 Comments

But even if I dont use const, just use int I get same errors... How can I fix this?
Removing const is not the solution. My answer was pointing out the reason it is not working. You can just use defines everywhere.
I cant really, some functions depend on arrays.
2

cnicutar gives the answer to your question.

A possible work-around still following the DRY-principles would be:

#define FOO_0 (9000)
#define F00_1 (4400)
...

const int foo[NUM] = {
  FOO_0,
  FOO_1,
  ...
};

const int bar[NUM] = {
  FOO_0 / (DEFINE1* DEFINE2),
  FOO_1 / (DEFINE1* DEFINE2),
  ...
};

1 Comment

I could use this, but the problem is I have another array that uses variables from bar... Is there another way? Its not necessary to use const int.

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.