How does the increment operator work in an if statement? - c

#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;
}

Related

what is the meaning of "!x" in "while(!x && i < n)"

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

Why is the output "false2", when the condition at the if block is 1 which is true? [duplicate]

This question already has answers here:
What is the difference between ++i and i++?
(20 answers)
Closed 2 years ago.
Why is the output "false2", when the condition at the if block is 1 which is true ?
#include<stdio.h>
int main(){
int x=0;
if (x++)
printf("true1");
else if (x==1)
printf("false2");
return 0;}
x++ means first use the value of x and then increment it's value by 1. So your if condition is if(0), Then x value increments and becomes 1. So your else if condition is else if(1). Whereas ++x means first increase the value of x by 1 and then use it so your first condition is if(1).
when the condition at the if block is 1 which is true ?
That's not the case. The if condition is actually false.
The expression x++ yields the current value of x (which is what's used to test the condition) and then increments it. Since x's current value is 0, it evaluates to false and thus it goes into the else if condition.
Contrast this with ++x which increments first and then yields the new value.
See C: What is the difference between ++i and i++?
The first time x is tested, it is zero and then it is incremented:
//x is post-incremented, i.e. evaluated before being incremented
int x=0;
if (x++)//x is tested when x==0, then is incremented
printf("true1");
else if (x==1)//execution flow goes here...
printf("false2");//...then here
To make x test as TRUE on the first iteration change it to a pre-increment:
//x is pre-incremented, i.e. incremented before being evaluated
int x=0;
if (++x)//x is incremented, then tested when x==1
printf("true1");//execution flow goes here...
else if (x==1)
printf("false2");
//...then here

What does the exclamation point in if (!strcmp() ... do?

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

Unintentional infinite 'for' loop

I just started programming in C, and while practicing with for loops, I came up with the following piece of code:
#include <stdio.h>
int main()
{
int x;
for (x=0;x=10;x=x+1)
printf("%d\n",x);
return 0;
}
When I run the code, I fall into an infinite loop. In my C manual it says that the condition x =10 is always true, but I can't get my head around it. If I give the variable x a value of 0 at the beginning, should the for loop not even start, or when the value of x reaches 10, shouldn't the loop stop?
Thanks in advance!
The condition part of your for loop is wrong. What you are doing is :
for (x = 0; x = 10; x = x +1) {
// Operations
}
The condition you have got here is x = 10 which is an affectation. So x = 10 will return 10, which also means true. Your for loop is equivalent to :
for (x = 0; true; x = x + 1) {
// Operations
}
This is why you have got an infinite loop, you should replace the affectation operator = by the comparason one with two equals sign ==. This means the for will loop while x is equals to 10.
EDIT : As Virgile mentioned in comments, for the second for loop, x will go from 0 to INT_MAX, then the behavior is undefined. So, your code is more likely to look like :
for (x = 0; true; x = 10) {
// Operations
}
When entering a for loop, the initialization part is performed first. So after the loop initialization x is 0.
Before entering the body of the loop, even the first time, the condition is checked. The "condition" in this case does not compare x to 10 but sets it to 10 since you are using = instead of ==.
Since an assignment as an expression has the value of the variable after assignment, the conditional expression has a value of 10 since that is what was assigned to x. Because this value is non-zero, it evaluates to true, and always will.
The problem here is, Take a close look on the condition part(2), in this what x=10, means is it is just assigning the value 10 to x, and it returns "True" always, so no problem what you have incrementing, it comes to 10 always, Thus infinite loop.
What you are trying to do is, you are implicitly converting int to bool in this line:
for (x=0;x=10;x=x+1)
^^^^
here, x=10; results true
So, it prints 10 everytime as you are using the = assignment operator.
for(int x=0;true;x=x+1)
What you could do to maintain the loop?
Use relational operators:
for (x=0;x!=10;x=x+1)
for (x=0;x==10;x=x+1)
for (x=0;x<10;x=x+1)

How is i==(20||10) evaluated?

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

Resources