Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while loop in C# with multiple conditions

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?

like image 434
Heidi Avatar asked Sep 24 '13 08:09

Heidi


People also ask

What is a while loop?

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".

What is while loop with syntax?

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.

What is Do While statement in C?

The do-while statement lets you repeat a statement or compound statement until a specified expression becomes false.

Is while () valid in C?

The code while(condition); is perfectly valid code, though its uses are few.


1 Answers

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) { /* ... */ }
like image 155
Gene Avatar answered Sep 22 '22 23:09

Gene