This question already has answers here:
How is i==(20||10) evaluated?
(2 answers)
Closed 7 years ago.
#include <stdio.h>
int main(void)
{
int i=10;
if(i==20 || 30)
printf("True");
else
printf("False");
return 0;
}
//Gives output:True
//Please tell me how this if loop is getting evaluated
There is no loop here..
Just one condition check, which has the following condition.
if(i==20 || 30)
First, you should know, any non-zero value is taken as True in a condition check.
So, first i is checked with the value 20, if thats true then True is printed, else it checks the next condition as there is an OR inbetween. SInce the next condition is non-zero which is always true, therefore it goes inside and prints True.
NOTE: This program will always print True, as the next condition is always true, and there is an OR in between which needs only one of the conditions to be true.
I have a feeling you want to check "if i is 20 or 30". The syntax for that is "if ( i is 20 ) or (i is 30)". The translation of that logic into code is:
if ( i == 20 || i == 30 )
When you use
if ( i == 20 || 30 )
it is translated as:
if ( (i == 20) || 30 )
regardless of what (i == 20) evaluates to, the conditional expression will always evaluate to "true" since 30 is a non-zero value.
Your if statement as two conditions
First is (i==20) and second is 30
The second conditions is 30 which is always true.
For "OR" operation any one true is enough to execute the if statements
So the statements under if are executecd
In your code:
i==20 give result false because i=10
i==20 || 30 equals to false || 30 give results true because 30 (or non-zero values) equal to true in condition check.
It should be:
if((i==20) || (i==30))
The expression if(i==20 || 30) is turning out to be true(non zero) hence you are seeing the output as true. The expression will be evaluated according to the precedence at which the operators get evaluated. == has higher precedence than || hence i==20 will be evaluated first and the result becomes as follows
if( true || 30 )
Now the operator is || the Left operand will be checked first which is true and control enters if block and prints true. This is called short circuit evaluation. If we have logical || operator, first the Left operand will be evaluated. If the left operand is true compiler wont evaluate right operand.
Related
So I saw this in my text book and I cannot understand how it works.
x=0;
int i = 0;
int n;
while(!x && i < n){
if(array[i]==target)
x=1;
else
++i;
}
what I don't understand is how "!x" works in loop's condition.
what I understand is this loop keeps running until it runs n times or when array[i]==target, which will change the value of x = 0 to x = 1 and stop the loop.
what I tried:
I tried replacing !x to x==0 and it did the same job.
The short answer here is that it does not matter what !x is because it is surrounded with undefined behavior completely nullifying its effect.
In the statement
While(condition) {...}
condition must resolve to either true or false, and must therefore be logical expression.
Given:
int x=0;//This answer assumes 'int' here as not specified in OP
int i = 0;
int n;
while(!x && i <n)
Because x is initialized as 0, equivalent to false the expression !x resolves to true, satisfying part of the condition.
Because n is not initialized however, the condition (!x && i <n) invokes undefined behavior, making the results of the overall condition unknown at the time of first entry, i.e. it can be either true or false. Further more, n does is never modified within {...}, so if the initial path happens to enter the brackets, the condition will change only due to changes in i. But again, because the value of n is not known, only undefined behavior will occur.
I don't know what language this is but !someVar is typically shorthand syntax for "variable is false", or another way of writing someVar == false. And in binary 0 is false and 1 is true. In the C language, 0 is false and anything not 0 is true. Therefore, in your loop, while !x is shorthand syntax for while x == false or while x == 0. Again, generally speaking since we don't know the language.
While(!x) means if x is a condition then we go into the while loop, only if the condition does not satisfy.Here in your code you have assigned x as zero,so !x means 1 because '!' Basically means opposite if x =0 then !x =1, if x=1 then !x=0 (all numbers greater than 1 are also considered as 1 only) so while(1 && i<n) is what happening here in the next step.If i<n is true then you will enter into the loop. If i<n is false the you won't enter the loop.
while(!x)
{
intructions;
}
means that your instructions will only keep running over and over again if x is false or equals 0 and will stop executing instructions once x becomes true or different from 0
Can someone explain what the exclamation point in the if statement does (i.e. !strmcp)?
string names[] = {"EMMA", "RODRIGO", "BRIAN", "DAVID"};
// Search for EMMA
for (int i = 0; i < 4; i++)
{
if (!strcmp(names[i], "EMMA"))
{
printf("Found\n");
return 0;
}
}
printf("Not found\n");
return 1;
For an if statement, if the expression evaluates to 0, then the block of code following the if statement is not executed. Any other value (positive or negative), will result in executing the code block. The function strcmp uses 0 to say that strings are equal because less than 0 is used to differ from greater than 0.
So in this code, we want printf("Found\n"); to be executed when the strings are equal. Since strcmp results in 0, we need to negate the value so that it becomes 1 which will result in executing that code block.
strcmp() returns 0 if the strings are identical, so you need to negate it, if you use it in an if clause to assert a true statement.
If your clause is if(0), the code inside the condition will not be executed.
For completion, it returns negative if the first different character found is lower in the first string, for instance:
first parameter string: "abca"
second parameter string :abcd"
This will return negative. If it's the other way arround it will return positive.
Also, string is not usually used in C (I refer you to Jonathan Leffler's commment), you can use char*:
char *names[] = {"EMMA", "RODRIGO", "BRIAN", "DAVID"};
Unary operator ! is called the logical NOT operator (cf., for example, this definition at cppreference.com). ! expression returns 1 if expression evaluates to 0, and it returns 0 if expression evaluates to anything else but 0.
So the condition in if (!0) gives 1; this means, the condition is met and the if-block is entered. It has the same meaning as if(0==0)
Consequently, the meaning of
if(!strcmp(names[i], "EMMA"))
in your code is exactly the same as
if(0==strcmp(names[i], "EMMA"))
And you already know when strcmp returns 0...
The exclamation point is the C's boolean negation character.
It means give me the boolean opposite of the value. A boolean is either true or false, which are 1 or 0 in the C Language.
In C, if statements execute their conditional statements if the argument is true.
if (a) means if a is true (i.e. non-zero)
if (!a) means if a is false (i.e. 0)
Therefore:
if (a) is the same as if (a != 0)
if (!a) is the same as if (a == 0)
Sometimes you'll see code that uses two exclamation points in a row "!!"
For example:
int a = !!b;
That ensures a will be ONLY 0 or 1, regardless of what the value of b is.
If b is ANY non-zero value, the ! operator will treat it as though it is true true, which it treats as being the same as 1
So:
!0 == 1
!1 == 0
!52 == 0
!25692 == 0
The second ! does the boolean inversion again, so:
!!0 == 0
!!1 == 1
!!52 == 1
!!25692 == 1
In C any non zero value is considered ad the logical truth, zero i considered as logical false. ! is a logical negation. So !0 (not false) will be the truth and if(!strcmp(str1,str2)) {statements} statements will be executed when str1 will be same as str2
Entry level comp sci major here.. I'm certain this question likely has an obvious answer, but I simply can't figure out why the following code produces an infinite loop and it's driving me insane. I understand that Math.random() returns a double value which when multiplied by 10 moves the decimal once to the right and the (int) typecasts the double data type to an integer by truncating the rest of the digits after the decimal point.. but then why on earth is the following code producing an infinite loop one of the boolean expressions will eventually produce a true value?
Now if I use && instead of || in the loop, it will work just fine because the && checks both expressions for a true yield prior to determining the outcome of the entire expression. Ah.. help..
int x;
do {
x = (int)(Math.random() * 10);
}
while (x != 1 || x != 0);
It is actually quite simple: Your variable 'x' can not be two different integer values. It does not matter if your variable is 0,1,2,3,4,5,6,7,8 or 9. Your while condition will always be true and therefor your loop will always run forever.
e.g:
x = 0: (x != 1 => true || x != 0 => false) => true
x = 1: (x != 1 => false || x != 0 => true) => true
x = 2: (x != 1 => true || x != 0 => true) => true
...
a while loop continues while the condition is true.
The condition you wrote is trivially always true for any value of x.
And number is always "different from 0" or "different from 1" (or both).
Hence, the infinite loop.
Maybe you thought `||, the logical 'or', meant "either the first one or the second is true, but not both" ?
If you want to have "x != 0 or x != 1, but not both", then you actually meant x == 0 || x == 1
I think I understand my erroneous thinking now.. with an || expression, if the first expression evaluates to false, the second is always also evaluated. I was under the impression that similar to &&, if one expression in an || is false, the entire is interpreted as also false, but turns out (false || true) = true while (false && true) = false as well as (true && false) = false, but unlike the ||, in an &&, the compiler doesn't even bother evaluating the second expression when the first yields false but an || evaluates both only if the first is false. I think I got it...
This code is always printing
fine Rs. 1
Despite number of days entered is > 30. What is the reason?
#include<stdio.h>
int main(void)
{
int days;
printf("enter no. of days");
scanf("%d",&days);
if (days<=5){printf("fine 50 paise");}
else if (5<days<=10){printf("fine Rs. 1");}
else if (10<days<30){printf("fine Rs.5");}
else printf(" memebership cancelled");
}
change
if (5<days<=10)
to
if (5<days && days <= 10)
same for other(s).
Otherwise, in your code, the condition check behaves like
if ( (5 < days) <=10)
so, whatever value you enter for days [6 and above, keeping the first if in mind], the result of the < operation will always produce either 0 or 1, both being <= 10, thus making the condition TRUE, printing fine Rs. 1.
Related Reading: C operator precedence.
Note: It's a good practice to add a return statement before the closing } of main()
C parses statements (such as if(5<days<=10)) in pieces, rather than trying to interpret them holistically. What this means is that the compiler reads if(5<days<=10) as if((5<days)<=10). Note that this means that the result of 5<days is compared to 10, not the variable days. To expand, the result of any comparison operator (<, >, ==, etc) is an integer representing whether it is true or false (this is called a boolean value, a value which is either true or false), 1 or 0 respectively. So, assuming 5<days is true, the next comparison is 1<=10 (or 0<=10 if days is smaller than 5), which of course is always true.
To fix this, use the comparison operator && (and). if(5 < days && days <= 10) is parsed as ((5 < days) && (days <= 10)), so you are correctly first comparing the days variable to 5 and 10, then taking the truth value of each of those statements and seeing if 5 < days and days <= 10 is true.
One last point - 0 is always false, any non-zero is always true, so if(0) will always be false and if(5) will always be true.
It's due to the second if condition, i don't know if it is allowed to use condition the way you used in you code as:
if (5<days<=10)
edit it to
if(days > 5 && days <= 10)
and it will work, also edit the third condition accordingly.
if (5<days<=10)
is not of the right syntax
it should be
if(5<days && days<=10)
change it and your problem should be solved. :)
int i=0;
if(4||1&&++i)
{
printf("%d",i);
}
O/p=0
But according to me o/p should be 1 due to preincrement....plz explain
When we use || it will check if first condition is false then it will go to second condition and so on, however the moment it finds a true condition it will return 1.
In this case 4 is true so it will not evaluate further statements here 1 && ++i and it will directly go to print("%d",i);
As you have initialize i to 0 it will print the value 0.
If you want if condition to evaluate 1 && ++i also, then in place of || (OR) use &&(AND).