-2

As you know, static arrays are much faster than dynamic. C++ allows you to set the size of a static array like:

const unsigned int size = 5;
unsigned int data[size];

Now, I heard it's possible to change the value of the const.

a) First of all how to change the value of the const?

b) If I do the following:

const unsigned int size = 5;
somehow change the value of size to 65
unsigned int data[size];

What I lose? Seems too good to be true?

Luka
  • 1,761
  • 2
  • 19
  • 30
  • 4
    Modifying `const` data is *undefined behaviour*. So you cannot rely on a program that does it. It is not a good idea to write unreliable programs, so it is not a good idea to "mess up" with consts. – juanchopanza Jan 19 '14 at 12:19
  • *"I heard it's possible to change the value of the const."* That's called hearsay. :) – jrok Jan 19 '14 at 12:19
  • BUT those people do that: http://stackoverflow.com/questions/583076/c-c-changing-the-value-of-a-const – Luka Jan 19 '14 at 12:20
  • @Luka First comment on that question: "Even if you get it to compile. it is undefined behavior." – Borgleader Jan 19 '14 at 12:21
  • 3
    Even if you can change the value of the const, the size of the array is determined during compilation. It will be fixed. – StoryTeller - Unslander Monica Jan 19 '14 at 12:21
  • "As you know, static arrays are much faster than dynamic." -- do we? Can you elaborate what exactly you mean by static and dynamic arrays and *how* one is faster than the other? –  Jan 19 '14 at 12:21
  • I mean the array I posted above is MUCH faster than malloc or vectors, I have tested this. It's faster because it doesn't waste time allocating memory I guess. – Luka Jan 19 '14 at 12:22
  • Ah, so you man faster to allocate. Yes, that's true, just not very interesting most of the time: Often, allocation speed is not the bottleneck, or you *can't* use stack allocation, or you don't need to allocate at all because you already have some allocation lying around. –  Jan 19 '14 at 12:25
  • "As you know" followed by something extremely questionable... – Kerrek SB Jan 19 '14 at 12:28
  • C'mon, don't down vote my question because of this – Luka Jan 19 '14 at 12:28
  • You should note that the whole endeavor is somewhat pointless. Constants are a tool to make code more human intellegible (so you can read "size" instead of some obscure and maybe ambiguous number). If you want a size of 65, then give your constant that value. Don't try to be super smart and cheat the compiler. There's nothing to be gained, even if it accidentially "works". – Damon Jan 19 '14 at 12:37

1 Answers1

1

It's possible (see this answer) but result will be pretty undefined. This constant will be inlined in many places by compiler, that's why resulting code will be fast. So you'll see size = 65 in some places and size = 5 in others.

Community
  • 1
  • 1
Odomontois
  • 15,918
  • 2
  • 36
  • 71