views:

227

answers:

5

This has the functionality I want (and it works)

#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;
}

However, I would like this to happen:

#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;
}

How can I have the something variable update each time the inner while loop is called? I know it has something to do with & or * for references and pointers but I haven't been able to find an example online about this.

Also I cannot edit anything within the foo() function.

Thanks.

+1  A: 

To represent a function in a variable use a function pointer

 int (*something)() = &foo;
Ryu
+6  A: 

Since foo() is returning a value, you need to call the function again to get the latest value. The concise way to do that in C is to do the assignment and check together:

while ((something = foo()) == 1)
{
     // do something
}
R Samuel Klatchko
+8  A: 

I think this is what you mean: it uses the function pointer to represent the function foo. Later it assigns it to a function 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

    }

}
rlbond
Depending on the details, it may be worth considering a for loop - "for (something = something () == 1; something = "
Steve314
A: 

How about this for your loop:

while(true) 
{
    int something = foo();
    // do whatever here

    if (!something) continue;
    do 
    {
      //do something
    } while(foo()==1)

    //does other unrelated things
}

This is assuming, from your example, that you want to have the something variable to do stuff with before the loop, and don't want a new call to foo() before going into your loop.

If not, then as mentionned in another post you can just do while(something = foo()) == 1)

JRL
A: 

Well try Void foo () {

cout<<"HAHA IM ANOTHER FUNCTION"; }

H4cKL0rD
-1 for not answering the question
Bob Kaufman
And `<<` is not part of C, but rather C++
voyager