c - 如何在无限循环中仅运行一个函数一次?

标签 c function infinite-loop

我正在用 C 语言编写一个游戏引擎,它可以在多个旧平台上运行,例如 Sega Saturn 和 PS1。不过,我遇到了一个小问题。游戏有一个主循环,所有其他函数都从该循环中调用。这意味着在不涉及状态的情况下很难只调用一次函数。所以,我需要知道最好的方法。我将展示一个关于如何设置的简短示例:

mainloop() //This function repeats forever
{
    myFunc1(); //Therefore, this function also repeats forever.
}

myFunc1() //Subsequent, gameplay related function
{
    if(myThing == 9){  //This thing is gonna equal 9 for quite a while, so that means the fucntion below will also be called like a bunch. But we don't want it to!
        runFuncOnce(); //Run this function only one time
    }
}

runFuncOnce() //I only want this function to do stuff one time until the next time it gets called!
{
    //Some examples of things you'd only want to do one time:
    PlayASound(MySound);
    ResetAnimation(MyAnimation); //Set an animation back to its first frame
    myVariable = 5; //Set this variable to whatever, but only once!
    printf("Hey, you did a thing. Good job! If you're lucky you won't see this text like 8 billion times in a row")
}

当然,您不想在同一个函数中执行这些操作,但您明白了。有一些愚蠢的方法可以做到这一点,但我正在尝试以最干净、最快的方式做到这一点。我不想谈论我的做法,因为人们很可能会关注我之前尝试过的方式,并尝试解决这个问题。给我新鲜的想法!相信我,我以前的做法既愚蠢又缓慢。这就是我来这里的原因!

最佳答案

您可以使用静态变量。

myFunc1() //Subsequent, gameplay related function
{
    static bool runOnlyOnce = false;

    if(myThing == 9) {  //This thing is gonna equal 9 for quite a while, so that means the function below will also be called like a bunch. But we don't want it to!
        if (runOnlyOnce == false) {
            runFuncOnce(); //Run this function only one time
            runOnlyOnce = true;
        }
    }
}

静态变量值在函数调用之间保持不变。因此,当下次调用 myFunc1() 时,它会找到 runOnlyOnce 变量 true 的值,并且不会调用 runFunOnce()再次

关于c - 如何在无限循环中仅运行一个函数一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47603663/

相关文章:

c# - 如何检测和避免无限循环?

c - SDL 访问冲突

c - 实现一个像设备一样的菜单,每个命令都没有条件

c++ - 为什么无限递归会导致段错误

c# - 在 DB4O 中按类型查询

mysql - 错误代码 : 1305 MySQL, 函数不存在

jquery - 如何在Grails上使用jQuery脚本?

c++ - 我的程序一直在循环,永远不会到达 "return 0;"。是编译器不好还是代码不好?

c++ - 无限循环会自行结束吗

c - 使用系统时 printf 不提供输出