Reputation: 51
printf("What do you do?\n1. Walk Away.\n2. Jump.\n3. Open Door.\n\n");
scanf("%d",&Choice);
printf("\n\n\n");
while(4<=Choice,Choice<=0);
{
printf("That is not a choice.\n");
printf("What do you do?\n1. Walk Away.\n2. Jump.\n3. Open Door.\n\n");
scanf("%d",&Choice);
printf("\n\n\n");
}
So this is my program. It works but what I want it to do is to repeat until an answer of 1, 2, or 3 is put in. But no matter what the answer is it has it go through the while loop then continue regardless of the next choice. (Also, I did declare "Choice"; I just didn't want to show the whole program.)
Upvotes: 0
Views: 99
Reputation: 14323
There are two problems in your code. Your while-loop expression is incorrect. The comma does not do what you think it does: in C/C++, the comma executes the left-hand expression and evaluates to the right-hand expression, meaning that in your case you are only checking the second condition. You probably want:
while(4<=Choice || Choice<=0)
The ||
is the OR operator, which returns true if either of the expressions around it are true.
Secondarily, there is a misplaced semicolon at the end of the while loop:
while(4<=Choice,Choice<=0); //<-- this should not be here
This marks the end of the loop, meaning that your code is parsed as:
while(4<=Choice,Choice<=0); //loop body is empty
{
//and we have a random unnamed block following it
}
Remove the semicolon and your while loop should execute correctly.
Upvotes: 6
Reputation: 308530
The comma operator ,
doesn't test both conditions, it simply returns the second of the two. So your while
loop is the equivalent of:
while(Choice<=0) ;
and since there's a ;
following the statement, it is in fact an infinite loop if the condition is met. Good thing you didn't enter a choice of -1.
Upvotes: 2
Reputation: 755064
C and C++ have a comma operator, which has the lowest precedence of all operators. It evaluates the left operand and throws the result away, and then evaluates the right operand. Thus, your while
condition is equivalent to:
while (Choice <= 0)
You also have a bug because there is a semicolon immediately after the condition, which makes for an infinite loop if Choice
is not strictly positive (because nothing in the loop changes the value of Choice
).
What you probably intended to write was:
while (Choice >= 4 || Choice <= 0)
{
...
}
Upvotes: 3