#include <stdio.h>
int main(void)
{
int i=10;
if(i==(20||10))
printf("True");
else
printf("False");
return 0;
}
This gives the output False.
Please explain to me how does this program work?
This line if(i==(20||10)) always evaluates to i==1 as Alk said in comments - (20||10) evaluates to 1, hence when you compare i == 1, that is why you get False as the output. A non-Zero value in C implies true.
Read about Short-circuit evaluation
Perhaps this is what you wanted:
int i=10;
if(i==20 || i == 10)
printf("True");
else
printf("False");
look at if(i==(20||10)). Due to the inner parentheses, 20||10 is evaluated first, yielding 1. Then, variable i, whose value is 10 is compared to 1, resulting 0.
In C, and 0 stands for False, while all non-zero values means True. So the condition comes to be False. Thus, "False" is printed.
Related
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
This question already has answers here:
What does the comma operator , do?
(8 answers)
Closed 3 years ago.
One of my friends ask me about this code and I and he are unable to find out, what is happening in the if condition. Can you guys explain how this condition works?
int main()
{
int i;
if (i = (1, 2, 0))
printf("Mehrose");
else
printf("Hello ");
printf("%d\n", i);
return 0;
}
The output for this code is Hello 0
First, formatting as the compiler sees the code we get:
int main(void)
{
int i;
if(i=(1,2,0))
printf("Mehrose");
else
printf("Hello");
printf("%d\n",i);
return 0;
}
The if statement can be broken down:
Comma operator , is evaluated first, left-hand side of the operator is discarded. This repeats for each operator:
if(i=(1,2,0))
if(i=(2,0))
if(i=0)
The assignment operator = assigns a value of 0 to i, and returns the right-hand side of the expression:
if(0)
Recall that 0 is evaluated as false (is "falsy") and 1 is evaluated as true (is "truthy"). Thus the first condition fails and the second block is executed. "Hello" is printed to the standard output stream, followed by "0".
In the expression,
i=(1,2,0)
you're using the comma operator, which evaluates all its operands and yields the result of its rightmost operand - which is 0 here.
So 0 is assigned to i.
So it's equivalent to if (i = 0), which assigns 0 to i and yields the value of i which is false and thus it prints the string in the else branch.
In gcc, I see that
int a=(b=0);
assigns a with 0 as well. Also I learnt that an assignment is an expression with the value and assignment associated from right to left.
Now one would expect the assignment, a=0 would evaluate to false when used as part of a condition. But it is not the case. if(a=0) would always evaluates to true. Could someone explain the reason behind this or am I missing something obvious?
Now one would expect the assignment, a=0 would evaluate to false when used as part of a condition.
It does.
#include <stdio.h>
int main()
{
int a = 456;
if (a=0)
puts("(a=0) evaluates to true");
else
puts("(a=0) evaluates to false");
return 0;
}
$ ./a.out
(a=0) evaluates to false
Whatever you were using to test your assumption must have been incorrect.
#include <stdio.h>
int main()
{
int k=5;
if(++k < 5 && k++ / 5 || ++k <= 8)
{
printf("%d",k);
}
return 0;
}
Why is the output 7 and not 8?(I am a beginner in programming so please bear with me.)
Operator precedence and logical expression short circuit evaluation.
The && in your logical condition binds more tightly than ||, so your conditional is equivalent to:
((++k<5 && k++/5) || ++k<=8)
It's easier to read code when it is presented in a structured way, like this:
int main() {
int k=5;
if ((++k<5 && k++/5) || ++k<=8) {
printf("%d",k);
}
return 0;
}
And now a blow-by-blow of the execution.
k starts at 5.
++k<5 advances k to 6, which is not <5.
The second half of the && expression is never evaluated, because 0 && ANYTHING == 0.
Because the left hand side of the || is 0, the right hand side is not short circuited. It must be evaluated.
++k<=8 advances k to 7, which is <=8.
Total conditional evaluates to 1 because right hand side of || is 1.
The "then" clause of the if statement is executed.
Current value of k, which is 7, is printed.
The program returns 0, and terminates.
It's also worth noting that the second half of your && clause is perhaps not doing what you intended. k++/5 is integer division, and since k>5 at all times, k++/5 will always be >=1 and thus always true.
#include <stdio.h>
int main()
{
int x = 0;
if (x++)
printf("true\n");
else if (x == 1)
printf("false\n");
return 0;
}
Output:
false
Why is the output false?
x++ is post increment; this means that the value of x is used then it is incremented.
If it is so, then x=0 should be used and the answer should be true.
In C, 0 is treated as false. In x++, the value of x, i.e, 0 is used in the expression and it becomes
if(0) // It is false
printf("true\n");
The body of if doesn't get executed. After that x is now 1. Now the condition in else if, i.e, x == 1 is checked. since x is 1 , this condition evaluates to true and hence its body gets executed and prints "false".
Post increment means that it returns the current value (in this case for the purpose of the if) and increments it afterwards. It is equivalent to
if(x) {
x++;
// ...
} else {
x++;
// ...
}
0 is equivalent to false in C. As you are using post-increment operator, condition is evaluated before increment so x is false and printf("true\n"); is never executed. Then goes to else and succeeds evaluating x == 1, then prints false.
As a good practice, try to avoid assignations in condition sentences.
0 is false in C. You're using the post-increment operator.
You yourself wrote: "x++ is post increment, this means that the value of x is used then it is incremented"
Consider what that means:
x is 0
The expression is evaluated, 0 is false, so the expression is false.
The post increment happens, changing x from 0 to 1. (After the expression was evaluated)
My opinion is that a better response to the relation between 'if' statement and the post increment operator '++' requires the expansion of your C-code into Assembly.
Trying to figure it out under the constricting logic of blocks of the "if ... else" statement, of high level languages, might be misleading because the flow control is read in different terms.
Consider that the pre and the post operators rely on the "change-then-use" and on the
"use-then-change" rules respectively, where 'change' is meant by 'increment' and 'use' by the 'comparison'.
So your input C-code basically turns into this raw pseudo-assembly:
; evaluating the first condition
mov x,0 // set x = 0
cmp x,0 // use (for comparison)
inc x // then change (now x is 1)
je print1
; evaluating the second condition
mov eax,1
cmp eax,x // evaluates to true
je print2
print1:
printf("true\n");
print2:
printf("false\n");
Take care that compilers might not put the inc instruction at the same position, that is, at the top or at the bottom of the labelled block of instructions.
Hope it helps!
I believe this simply could fix the error
#include <stdio.h>
int main()
{
int x = 0;
if (++x)
printf("true\n");
else if (x == 1)
printf("false\n");
return 0;
}