c - 错误: initializer element is not constant (how can I implement this?)

标签 c function time compiler-errors

我了解到我收到 initializer element is not constant错误,因为我尝试将调用分配给 clock()startTime里面TimerstartTime是静态的(这意味着它的值只能是编译时已知的值)。

这是我的代码,我需要调用 (*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/

相关文章:

关于数组是 "zeroed out"的困惑

c - 如何在C中检查以dd-mm-yyyy形式输入的日期的数字?

将 float 转换为 char*

c - 将字符存储在字符串变量中

检查一个数字是否是另一个数字的镜像(其相反)

javascript - 如何使用 Javascript 动态生成输入字段,然后使用它们的值?

r - 对于每一行,输出具有最高值的前 5 列的列名,但省略 0

sql-server - 将小数时间转换为小时和分钟

java - 如何使用java预定执行器服务在一天的特定时间运行java代码?

c++ - timespec.tv_sec 总是返回 0