作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我了解到我收到 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/
我是一名优秀的程序员,十分优秀!