我了解到我收到 initializer element is not constant
错误,因为我尝试将调用分配给 clock()
到 startTime
里面Timer
和startTime
是静态的(这意味着它的值只能是编译时已知的值)。
这是我的代码,我需要调用 (*func)
每seconds
秒并且不确定如何实现这一点,那么做我需要的事情的好方法是什么?
static void Timer(void (*func)(void), int seconds)
{
static clock_t startTime = clock();
if ((startTime - clock() / CLOCKS_PER_SEC) > seconds)
{
startTime = clock();
(*func)();
}
}
更新
评论的人建议我做这样的事情,但如果我这样做if
开头是多余的:
static clock_t startTime = (clock_t) -1;
if (startTime == -1) startTime = clock();
else if ((startTime - clock() / CLOCKS_PER_SEC) > seconds)
{
startTime = clock();
(*func)();
}
最佳答案
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)();
}
}
关于c - 错误: initializer element is not constant (how can I implement this?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43968611/