1

For example I have:

int boo[8];
boo[1] = boo[3] = boo[7] = 4;
boo[0] = boo[2] = 7;
boo[4] = boo[5] = boo[6] = 15;

How I should type it as constant values? I saw similar question but it didn't help me.

EDIT: One more question what about if boo with indexes 0 1 3 4 5 6 7 is constant but boo[2] is not? is it possible to do it?

2
  • 1
    If by "constant values" you mean an initialization list, you can't. But some compilers provide interesting extensions. Take a look this question stackoverflow.com/questions/201101/… Commented Apr 7, 2011 at 13:47
  • Do you mean you want const int boo[8] ? Commented Apr 7, 2011 at 13:47

2 Answers 2

7

Is this what you are looking for?

const int boo[] = { 7, 4, 7, 4, 15, 15, 15, 4 };

Get a non-const pointer to one entry in the array like this:

int * foo = (int*)&boo[2];
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, one more question what about if boo with index 0 1 3 4 5 6 7 is constants but boo[2] is not?
Maybe you can access it via a different pointer: int const* boo2 = boo+2; And after *boo2 = 5;
I have modified the answer to include an example of getting a pointer you can use to modify one entry.
3

One not so elegant solution may be:

const int boo[8] = {7,4,7,4,15,15,15,4};

Another solution may be:

int boo_[8];
boo_[1] = boo_[3] = boo_[7] = 4;
boo_[0] = boo_[2] = 7;
boo_[4] = boo_[5] = boo_[6] = 15;
const int * boo = boo_;

2 Comments

Nah, it seems quite elegant to me :)
Use boo_ instead of _boo. Names starting with underscores, or double underscores, are reserved for use by the implementation(compiler). There are certain rules here but its probably just best to avoid the underscore at the beginning all together.

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.