Implicit type conversion and time measurement

Viewed 57

I'm implementing a game loop in c++ using the timeGetTime function like below:

    // ...
    DWORD oldtime = 0, newtime = 0, delta = 0;
    //...
    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {

        if (msg.message == WM_QUIT) {               
            exit(0);
        }

        TranslateMessage(&msg);
        DispatchMessage(&msg);

    }

    delta = newtime - oldtime;      

    while (delta >= MS_PER_UPDATE) {

        //update();
        delta -= MS_PER_UPDATE;
        g_loopCnt++;
    }
    //render();
    // ...

I know that the value returned by the timeGetTime function wraps around to 0 every 2^32 milliseconds, which is about 49.71 days as the official doc says. So is it possible (however, it is very unlikely) that the delta will be a negative number (when the newtime will pass the "magic" 2^32 milliseconds barrier). Lets take for an example VERY unlikely but theoretically possible case:

newtime == 304(dec)
oldtime == 0x7FFFF82F (2147481647 dec)

when the game is running longer then these 49.71 days. We'll get:

delta = 304(dec) - 2147481647(dec) == -2147481343(dec signed!);     
...
    while (-2147481343 >= MS_PER_UPDATE) {...}

So there is of course a resulting a negative numer (-2147481343) so on the fiest look it won't work here. BUT the compiler will make here an implicit conversion from signed to unsigned resulting in:

while (2147485952 >= MS_PER_UPDATE) {...}

and finally the code WILL work! (thanks to this implicit conversion) And here is my question. Is it ok/safe to let the code be simple like that and just rely on the implicit conversion made automatically OR maybe I have to take care of the "wrap around" problem myself doing some extra checking/coding?

P.S

If I cannot count on that automatically implicit conversion is it a good solution to just change the operand order when there is about to be an negative delta like below?:

if(newtime < oldtime)
    delta = oldtime - newtime;      
0 Answers
Related