Reputation: 375
I understand that I'm getting the initializer element is not constant
error because I try to assign a call to clock()
to a startTime
inside Timer
and startTime
is static (which means it's value can only be something that's known at compile-time).
Here's my code, I need to call (*func)
every seconds
seconds and am unsure how to implement this, so what would be a good way of doing what I need?
static void Timer(void (*func)(void), int seconds)
{
static clock_t startTime = clock();
if ((startTime - clock() / CLOCKS_PER_SEC) > seconds)
{
startTime = clock();
(*func)();
}
}
The people who commented suggestted that I do something like this, but if I do this the if
at the beginning is redundant:
static clock_t startTime = (clock_t) -1;
if (startTime == -1) startTime = clock();
else if ((startTime - clock() / CLOCKS_PER_SEC) > seconds)
{
startTime = clock();
(*func)();
}
Upvotes: 0
Views: 780
Reputation: 6003
static void Timer(void (*func)(void), int seconds)
{
static clock_t startTime = 0;
if(!startTime)
startTime = clock();
if ((startTime - clock() / CLOCKS_PER_SEC) > seconds)
{
startTime = clock();
(*func)();
}
}
Upvotes: 1