【问题标题】:error: initializer element is not constant (how can I implement this?)错误:初始化元素不是常量(我该如何实现?)
【发布时间】:2017-10-13 14:18:44
【问题描述】:

我知道我收到了 initializer element is not constant 错误,因为我尝试将对 clock() 的调用分配给 Timer 内的 startTimestartTime 是静态的(这意味着它的值只能是某物这在编译时就知道了)。

这是我的代码,我需要每隔 seconds 秒调用一次 (*func) 并且不确定如何实现它,那么什么是做我需要的好方法?

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)();
    }

【问题讨论】:

  • 你不能初始化一个不是编译时常量的值,但是你可以赋值给它。
  • 阅读静态关键字。它不限制它所使用的变量的动态变化。它更多的是关于变量的生命周期,尤其是在对函数的调用之间。另外,我同意@EOF。从赋值中拆分静态变量的定义。然后它将接受对函数的运行时调用的返回值。我假设你没有试图让它只被调用一次。
  • 一种方式:static clock_t startTime = (clock_t) -1; if (startTime == -1) startTime = clock(); else if ((startTime - clock() / CLOCKS_PER_SEC) > seconds) { /* your original code */ }

标签: c function time compiler-errors


【解决方案1】:
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)();
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 1970-01-01
    • 2011-03-02
    • 2012-06-04
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    相关资源
    最近更新 更多