Difference between static variables and normal variables.


Hello ,

I want to know the difference static variables and normal variables.
I am working on sdl game library in c++.

This is my game loop for which I want to control my frame rate.

bool quit = false;
while(quit == false)
{

//SDL_GetTicks returns the time in milliseconds
static int last_tick = SDL_GetTicks();
int this_tick = SDL_GetTicks();

// If still in the same tick, sleep
if (this_tick <= last_tick)
{
SDL_Delay(1); //Delays for 1 ms.
continue; // go back to the start of the loop
}

// Perform the necessary number of physics iterations
while (last_tick < this_tick)
{
// handle input here

// update everything here (moving objects and such things)

last_tick += 1000 / PHYSICS_FPS; //where PHYSICS_FPS = 100
}

// draw the scene here
}
Initially last_tick and this_tick contain the same value i.e the time completed
till now.
Here the game loop is updated every 10 ms.

But this is very hard for me to understand. Can any one explain me.
Also , How come last_tick can be different from this_tick?
Means how does the keyword static change it's behaviour.

I have heard static variables retain values from function call to call in c.
But i don't have any good example.can anyone provide me.

Thanks a lot for all your support cplusplus.com and its users.

Here's an example of a function that has a protection so that it is only called once:

1
2
3
4
5
6
7
8
9
10
void seedRand(int seed)
{
    static bool done_already; // Get's initialized to FALSE automatically per C++ standard

    if (!done_already)
    {
        done_already = true;
        srand(seed);
    }
}


In your code, you initialize last_tick with SDL_GetTicks(); but this isn't done after the initialization. Therefore, this_tick is updated, then last_tick is compared to this_tick, then you increment last_tick by 1000 and re-draw your stuff until you catch up to this_tick.
Topic archived. No new replies allowed.