Questions about compile time constants

Started by
11 comments, last by alvaro 10 years, 11 months ago
You are correct that a UDT that can trivially be replaced with a single immediate value can (and clearly will) be elided by a good optimizer.

I suppose I should clarify my earlier statement: UDTs that are non-trivial (i.e. more than one field, complex behavior, construction/destruction semantics, etc. etc.) will almost certainly not be elided by the optimizer, assuming there is no simplification that can be done to make it trivial.


Optimizing compilers can do strange and unexpected things, and for often unclear reasons, will fail to do things that look completely sensible but are in fact prohibited by some language spec or reality constraint. In general, trying to develop an intuition for compiler optimization is best done as a white-box exercise rather than black-box. To wit: look at the generated programs in a disassembler, don't try to guess.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Advertisement

I don't know what you guy means by "doesn't quite make sense" and "for obvious reasons". The following three programs generate the same executable byte for byte (using g++ 4.7.1):

Those are not arrays or structures, handling the constants there as the values directly is easy. Now consider this:

static const uint8_t dpcm_offsets[] = {
   0x00, 0x01, 0x02, 0x04,
   0x08, 0x10, 0x20, 0x40,
   0x80, 0xFF, 0xFE, 0xFC,
   0xF8, 0xF0, 0xE0, 0xC0
};

It's unlikely you'll declare an array of constants unless you pretend to access it as an array, which pretty much requires access through a pointer (even if implicitly), so stuff like this is pretty much going to end up in memory always. Similar deal with structures, especially as they're generally used to pass around large amounts of data rather than just for the sake of organization.

Don't pay much attention to "the hedgehog" in my nick, it's just because "Sik" was already taken =/ By the way, Sik is pronounced like seek, not like sick.

Those are not arrays or structures, handling the constants there as the values directly is easy.

How is `struct X' not a structure? You made a very general statement, and I showed you a counter example. You can try to make a more limited statement if you want it to be true.

Now consider this:

static const uint8_t dpcm_offsets[] = {
   0x00, 0x01, 0x02, 0x04,
   0x08, 0x10, 0x20, 0x40,
   0x80, 0xFF, 0xFE, 0xFC,
   0xF8, 0xF0, 0xE0, 0xC0
};


I tried an example with an array just like that, and still no differences.
#include <iostream>

static const int constants[3] = {4, 5, 6};

int main() {
  std::cout << constants[1] << '\n';
}
So what are those "obvious reasons" again?

This topic is closed to new replies.

Advertisement