Share via

Implicit type conversion and time measurement.

Daro911 1 Reputation point
2022-06-10T09:34:22.617+00:00

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;		  
Developer technologies | C++
Developer technologies | C++

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.


1 answer

Sort by: Most helpful
  1. Castorix31 91,876 Reputation points
    2022-06-10T10:26:02.01+00:00

    You can see the basic game loops in DirectX samples, like for example at : Introduction to DirectX 11
    (search PeekMessage on the page to go to the loop...)

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.