KaiserJohaan
KaiserJohaan

Reputation: 9240

Compilers evaluating constant expressions

I want my compiler (VS 2013) to avoid any redundant arithmetic calculations preferably by computing the following once at compiletime.

Basically I see three scenarios as below:

For example:

void Mesh::Draw1()
{
    const static uint32_t gStaticOffset = 0;
    const static uint32_t gVertexSize = sizeof(float) * 3;
    const static uint32_t gBoneIndexSize = sizeof(uint32_t) * MAX_BONES;
    const static uint32_t gBoneWeightSize = sizeof(float) * MAX_BONES;

    ...
}

vs

void Mesh::Draw2()
{
    const uint32_t staticOffset = 0;
    const uint32_t vertexSize = sizeof(float) * 3;
    const uint32_t boneIndexSize = sizeof(uint32_t) * MAX_BONES;
    const uint32_t boneWeightSize = sizeof(float) * MAX_BONES;

    ...
}

vs

const static uint32_t gStaticOffset = 0;
const static uint32_t gVertexSize = sizeof(float) * 3;
const static uint32_t gBoneIndexSize = sizeof(uint32_t) * MAX_BONES;
const static uint32_t gBoneWeightSize = sizeof(float) * MAX_BONES;

void Mesh::Draw3()
{
    ...  
}

My thoughts, please correct me if wrong:

Will the compiler generate different code for each of them and if so, which one avoids the most redundant calculations?

Upvotes: 0

Views: 116

Answers (1)

Cody Gray
Cody Gray

Reputation: 244712

There is no way to be certain what your compiler will do unless you try it. Compile all three code examples and then look at the resulting object code.

Practically speaking, they should all be identical. Constant folding is about the lowest of low-hanging fruit when it comes to compiler optimizations. If your compiler isn't calculating these constants at compile-time, it is not an optimizing compiler. Unless you have a very good reason for continuing to use it, you should consign it to the garbage heap and find a different one.

Upvotes: 4

Related Questions