Yashwanth CB Yashwanth CB - 24 days ago 6
C++ Question

Use and over use of static variables

Is it recommended to use static variables where ever I am comfortable with?

Because I tend to use it more often now. Is there any thing like using static variables is a bad practice or it will fill up the memory quickly?

Currently I am doing small games with c++. So to maintain some states like jump position and animation time I have to use static variables in a function and that function will be called multiple times in a loop. So static variables will do that Job. Is there any oo patterns to get over this problem?

void jumpit(){
static int jump ;
if( !jump && pressed)
jump=1;
if (jump)
obj.y++;
}


And in the loop I will call this to get the Job done..do we have any better idea to do the same??

Answer

Your "obj" could keep track of its own state.

A free standing jumpit function could be implemented as:

void jumpit(Object& obj, bool pressed)
{
        if( !obj.jump && pressed)
              obj.jump = true;
        if (obj.jump)
             obj.y++;
}

Or it might be better to implement jumpit as part of "Object"

It is almost never a good idea to keep state in a function.