使用变量表示C中的函数

827*_*827 0 c pointers function

这有我想要的功能(它的工作原理)

#include <stdio.h>
//includes other libraries needed

int foo();

int main() 
{
    while(true) 
    {

        while(foo()==1) 
        {
            //do something
        }

        //does other unrelated things

    }

}

int foo() 
{
    // Returns if a switch is on or off when the function was called 
    // on return 1;
    // off return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,我希望这种情况发生:

#include <stdio.h>
//includes other libraries needed

int foo();

int main() 
{
    while(true) 
    {
        //THIS IS THE PROBLEM
        int something = foo();

        while(something==1) 
        {
            //do something
        }

        //does other unrelated things

    }

}

int foo() 
{
    // Returns if a switch is on or off when the function was called 
    // on return 1;
    // off return 0;
}
Run Code Online (Sandbox Code Playgroud)

每次调用内部while循环时,如何更新某些变量?我知道它是与&*引用和指针,但我一直没能在网上找到这样的例子.

此外,我无法编辑foo()功能内的任何内容.

rlb*_*ond 8

我认为这就是你的意思:它使用函数指针来表示函数foo.后来它将它分配给一个函数bar:

#include <stdio.h>
//includes other libraries needed

int foo();
int bar();

int main() 
{
    while(true) 
    {
        int (*something)() = &foo;

        while(something()==1) 
        {
                something = &bar;
        }

        //does other unrelated things

    }

}
Run Code Online (Sandbox Code Playgroud)


R S*_*hko 6

由于foo()返回一个值,您需要再次调用该函数以获取最新值.在C中执行此操作的简明方法是进行分配并一起检查:

while ((something = foo()) == 1)
{
     // do something
}
Run Code Online (Sandbox Code Playgroud)