Reputation: 95
#include<stdio.h>
void main() {
int x = 0,y = 0,k = 0;
for(k = 0; k < 5; k++){
if(++x > 2 && ++y > 2) x++;
}
printf("x = %d and y = %d",x,y);
}
I'm not able to understand how the above piece of code generates x = 6 and y = 3.
RESOLVED : I didn't know that when there is &&, if the first statement evaluates to false the second will not be executed.
Upvotes: 0
Views: 298
Reputation: 29
&&
is the short-circuit operator.
if ( ++x > 2 && ++y > 2 )
in this if
statement the second operand will be evaluated only if the first one is true.
k=0
X
will be incremented by 1
. Now x
value is 1
. x > 2
is false. So Y
won't increase.k=1
X
will be incremented by 1
. Now X
value is 2
. X > 2
is false. So Y
won't increase.k=2
X
will be incremented by 1
. Now X
value is 3
. X > 2
is true . So Y
will be incremented by 1
. Now Y
value is 1
. but Y > 2
is false . So total if condition is false
.k=3
X
will be incremented by 1
. Now X
value is 4
. X > 2
is true . So Y
will be incremented by 1
. Now Y
value is 2
. but Y > 2
is false . So total if condition is false
.k=4
X
will be incremented by 1
. Now X
value is 5
. X > 2
is true . So Y
will be incremented by 1
. Now Y
value is 3
. Y > 2
is true . So total if condition is true
. Then X
will be incremented by 1
.Upvotes: 1
Reputation: 108938
&&
is a short-circuit operator.
The first time through the loop, only ++x
is evaluated.
The second time through the loop, only ++x
is evaluated.
The third time through the loop, both are evaluated.
...
Upvotes: 4
Reputation: 73366
Not related to your question, but please read What should main() return in C and C++? int
.
c enables short circuit, and &&
is an operator that follows that. So, this:
if(++x > 2 && ++y > 2)
says:
x
by 1.x
is greater than 2 (thus the first operand of &&
is true),
evaluate the second operand.y
by 1, and if y > 2
is
true, then the whole if condition will be true.Your code is equivalent to this:
#include <stdio.h>
int main() {
int x = 0, y = 0, k = 0;
for(k = 0; k < 5; k++){
x = x + 1;
if(x > 2)
{
y = y + 1;
if(y > 2)
{
x = x + 1;
}
}
}
printf("x = %d and y = %d", x, y);
return 0;
}
Upvotes: 3
Reputation: 239
if(++x > 2 && ++y > 2)
In this line if first condition is false it will not evalute second condition. So first condition is false until value of x is 3
Upvotes: -1