Yashwanth CB Yashwanth CB - 10 months ago 58
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)
if (jump)

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

Answer Source

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)

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.