Search code examples
c++functionopenglstatic-variables

Static variables in the scope of a draw function in OpenGL?


As an example, I have the following draw function in some OpenGL application:

void Terrain::Draw(float ox, float oy, float oz) {
    float terrainWidth = stepWidth * (width - 1.0f);
    float terrainLength = stepLength * (length - 1.0f);
    float startWidth = (terrainWidth / 2.0f) - terrainWidth;
    float startLength = (terrainLength / 2.0f) - terrainLength;

        (...)
}

Terrain is a class and I'm sure that the step and terrain width/length instance variables will never change during the lifetime of the object (they are initialized before the first call to the draw function).

Assuming my application runs at a steady 25fps, the function will be called 25 times a second. The values will never change, they will always be the same.

Would I gain anything in declaring those function variables as static? To prevent them from being destroyed and declared every time the function is called?


Solution

  • Would I gain anything in declaring those function variables as static?

    it's really a small amount of data: don't bother, unless you have a ton of instances.

    To prevent them from being destroyed and declared every time the function is called?

    this typically takes the form:

    class Terrain { 
    public:
        // interface
    protected:
        // more stuff
    private:
        // ... existing variables
        const float d_terrainWidth;
        const float d_terrainLength;
        const float d_startWidth;
        const float d_startLength;
    };
    

    then you can use the precalculated invariants from your Draw implementation.