samedi 21 août 2021

How to assign a value to a variable and check its value at the same time in a while loop in C?

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?

Aucun commentaire:

Enregistrer un commentaire