How to assign a value to a variable and also check its value in a while loop?

Viewed 479

I'm doing a time-critical application in C. I want to assign a value to a variable and check its value at the same time in a while loop to reuse it later in the body of this loop. The value assigned to the variable is returned by a function that takes some time to run. I know I can do something like that:

while (function_returning_int() <= foo) {
    bar(function_returning_int());
}

The problem is that this involves calling the same function two times. I tried doing that instead:

while ((int thing = function_returning_int()) <= foo) {
    bar(thing);
}

It gives me an error. I don't understand why since the assignment operator (=) returns the assigned value. How can I assign a value to a variable and check its value at the same time in a while loop?

3 Answers

You're close. You just need to declare the variable outside of the loop:

int thing;
while (( thing = function_returning_int()) <= foo) {
    bar(thing);
}

You have to store the result in a variable. To limit its scope one can use c99 syntax for 'for' loop.

for (int val; ( val = function_returning_int()) <= foo;)
    bar(val);

Try this instead. solution is assign value of variable which is declared inside the loop to another local variable.and then use variable in main method.declare the variable outside the while loop.

Related