Reputation: 3087
I have a problem with a timer class based on a SDL timer.
class CTimer
{
public:
CTimer(): startTick(0), endTick(0), curTime(0), running(false) {};
void Start() { startTick += SDL_GetTicks() - endTick; running = true; };
void Stop() { endTick = SDL_GetTicks(); running = false; };
void Reset() { startTick = 0; endTick = 0; curTime = 0; };
inline int operator()() { return running ? curTime = ((int) SDL_GetTicks - startTick) / 1000 + 1 : curTime; };
private:
int startTick;
int endTick;
int curTime;
bool running;
};
The () operator should return time in seconds (stored in curTime). But it always returns 4202 (curTime is always equal to that). What am I doing wrong?
Test code:
int main()
{
SDL_Init (SDL_INIT_TIMER);
CApp::CTimer timer;
timer.Start();
for (int i = 0; i < 15; ++i)
{
SDL_Delay (1000);
std::cout << timer() << '\n';
}
return 0;
}
Upvotes: 0
Views: 364
Reputation: 96271
In addition to the attempted call to SDL_GetTicks
instead of SDL_GetTicks()
causing it to take the address of that function (and always returning the constant as you observed), it looks like if you call Start
and then Stop
before calling operator()
you won't get a meaningful result.
Upvotes: 0
Reputation: 308256
This is a perfect example of why you don't want to use old-style C casts in C++.
(int) SDL_GetTicks
The missing parentheses on the function call mean you're casting a pointer to the function to an int, not the return value. Surprisingly enough the pointer to the function never changes.
Upvotes: 3
Reputation: 54168
For starters,
inline int operator()() { return running ? curTime =
((int) SDL_GetTicks - startTick) / 1000 + 1 : curTime; };
should be
inline int operator()() { return running ? curTime =
((int) SDL_GetTicks() - startTick) / 1000 + 1 : curTime; };
I would think.
Did you get a warning error about this?
Upvotes: 1
Reputation: 2009
Are you missing parentheses for SDL_GetTicks?
inline int operator()() { return running ? curTime = ((int) SDL_GetTicks - startTick) / 1000 + 1 : curTime; };
Upvotes: 1