Reputation: 117
#include <stdio.h>
void main()
{
int a = 11, b = 5;
if(a == 7 || 10){
printf("True");
}
else
printf("False");
}
This is my problem, i saw it in a question and was asked what the output would be. i put false but the answer was true, im trying to understand why because a is not equal to any of them and the condition for it to be true is that a be equal to at least one of them
Upvotes: 0
Views: 938
Reputation: 99
It is a logical error. The way you type it you don't check whether a == 7 OR a == 10 (as you wish), rather you check only if a == 7 and second condition if (10) is always true.
The fix is pretty simple actually:
void main()
{
int a = 11, b = 5;
if(a == (7 || 10)){
printf("True");
}
else
printf("False");
}
Upvotes: 1
Reputation: 225227
This:
if (a == 7 || 10)
Does not test if a
is equal to either 7 or 10.
The ==
operator will evaluate to 1 if both operands are equal, and 0 otherwise. The ||
operator will evaluate to 1 if at least one operand is non-zero, and 0 otherwise.
Also, the equality operator has higher precedence than the logical OR operator. So the above parses as:
if ((a == 7) || 10)
So the expression will be true if either a==7
evaluates to non-zero or 10
evaluates to non-zero. The latter is true so the condition is true.
Upvotes: 1
Reputation: 311108
The expression in the if statement
if(a == 7 || 10){
is equivalent to
if( ( a == 7 ) || ( 10 ) ){
As 10
is not equal to 0
then the second operand of the logical OR operator ||
always evaluates to the logical true. So the whole expression used in the if statement has a result of the logical true.
In fact as a
is not equal to 7
(due to its initialization) then the above if statement is equivalent to
if( 10 ){
Upvotes: 3