This is my code:
while( Func(x) != ERR_D)
{
if(result == ERR_A)
throw...;
if(result == ERR_B)
throw...;
mydata.x = x;
}
The problem is that I want to use result = Func(x)
in the while condition as the result will be checked inside the while loop. The while loop should call Func(x)
untill it returns ERR_D
.
I can't use
do{
result = Func(x);
if(result == ERR_A)
throw ...;
if(result == ERR_B)
throw ...;
mydata.x = x;
}while(result != ERR_D);
in my project as it first calls Func(x)
which is what I don't want.
But I have tried while(result = Func(x) != ERR_D)
, it doesn't work. Any ideas to solve this?
A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10".
The while construct consists of a block of code and a condition/expression. The condition/expression is evaluated, and if the condition/expression is true, the code within all of their following in the block is executed. This repeats until the condition/expression becomes false.
The do-while statement lets you repeat a statement or compound statement until a specified expression becomes false.
The code while(condition); is perfectly valid code, though its uses are few.
You just need to add some parentheses:
while((result = Func(x)) != ERR_D) { /* ... */ }
The !=
operator has a higher priority than the assignment, so you need to force the compiler to perform the assignment first (which evaluates to the assigned value in C#), before comparing the values on both sides of the !=
operator with each other. That's a pattern you see quite often, for example to read a file:
string line;
while ((line = streamReader.ReadLine()) != null) { /* ... */ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With