Why isn't the ++y part executing? [duplicate] - c++

This question already has answers here:
Is short-circuiting logical operators mandated? And evaluation order?
(7 answers)
Closed last month.
So here is the question I am given , I need to tell the output :
#include <iostream>
using namespace std;
int main()
{
int x = 10;
int y = 20;
if(x++ > 10 && ++y > 20 ){
cout << "Inside if ";
} else{
cout << "Inside else ";
}
cout << x << “ “ << y;
}
The ans given is Inside else 11 20 I checked with complier this is the correct answer but according to me the answer should be Inside else 11 21.
Why is this happening ? Why isn't the ++y part executing ?
I also tried y++ I still get same answer.

When you write x++, that means two things:
return current value
increment x
Since current value is 10 and 10 > 10 is false, the part after &&, including ++y, is not evaluated.
An alternative would be prefix increment, i.e., ++x.

If the first operand of the logical AND (&&) operator evaluates to false, the second operand is not evaluated, because the value of the expression is already known.
From the C++ 20 Standard (7.6.14 Logical AND operator)
1 The && operator groups left-to-right. The operands are both contextually converted to bool (7.3). The result is true if both operands are true and false otherwise. Unlike &, && guarantees left-to-right evaluation: the second operand is not evaluated if the first operand is false.
Also, the value of an expression with the post-increment operator is the value of its operand before incrementing.
From the C++ 20 Standard (7.6.1.6 Increment and decrement_
1 The value of a postfix ++ expression is the value of its operand...
So, in this if statement:
if(x++ > 10 && ++y > 20 ){
the left operand of the logical AND operator x++ > 10 evaluates to false. However, the side effect of the post-increment operator is applied to the variable x. The second operand ++y > 20 is not evaluated.
So, the control will be passed to the else statement, and within its sub-statement x will be equal to 11 and y will keep its original value 20.

Related

What is the principle of this code with i++?

Code
#include <iostream>
using namespace std;
int main()
{
int i = 1;
while (i < 10)
if (i++ % 2 == 0)
cout << i << endl;
return 0;
}
The output is
3
5
7
9
Since i is 1, I thought that the if statement satisfies 2% 2 == 0 and 2 should be output, but why 3?
if (i++ % 2 == 0) means evaluate i%2 and compare to 0, and increment i at some point after evaluating it but before cout << i
That's why you're seeing odd numbers printed. In every case, an even value of i caused the statement controlled by the if to be executed, and the increment changed the even value to an odd one.
You are using post-increment, which increments the variable and then returns the old value before the increment. You are then printing the incremented value.
So, lets look at your loop step-by-step:
On the 1st iteration, i is 1. i++ sets i to 2, but returns 1. So the if compares 1 % 2 == 0, which is false.
On the 2nd iteration, i is 2. i++ sets i to 3, but returns 2. So the if compares 2 % 2 == 0, which is true, so cout << i prints 3.
On the 3rd iteration, i is 3. i++ sets i to 4, but returns 3. So the if compares 3 % 2 == 0, which is false.
On the 4th iteration, i is 4. i++ sets i to 5, but returns 4. So the if compares 4 % 2 == 0, which is true, so cout << i prints 5.
And so on...
It sounds like perhaps you were expecting i++ to pre-increment instead, returning the new value rather than the old value. In which case, there is a slightly different syntax for that purpose:
#include <iostream>
using namespace std;
int main()
{
int i = 1;
while (i < 10)
if (++i % 2 == 0) // <-- ++i vs i++
cout << i << endl;
return 0;
}
Note the position of ++ in relation to i. Both syntaxes increment i, but positioning ++ to the left of i returns the new value after i is incremented, while positioning ++ to the right of i returns the old value before i was incremented.
Same with the decrement operator --, too. It has pre-decrement and post-decrement versions.
According to the C++ 14 Standard (5.2.6 Increment and decrement)
1 The value of a postfix ++ expression is the value of its
operand. [ Note: the value obtained is a copy of the original value
— end note ] The operand shall be a modifiable lvalue. The type of the
operand shall be an arithmetic type or a pointer to a complete object
type. The value of the operand object is modified by adding 1 to
it, unless the object is of type bool, in which case it is set to
true.
So for example in the second iteration of the while loop the variable i is indeed equal to 2 after incrementing it in the first iteration of the loop
while (i < 10)
if (i++ % 2 == 0)
cout << i << endl;
Thus the condition of the if statement
if (i++ % 2 == 0)
evaluates to true. But the value of the variable i after the evaluation of the condition was incremented. So this statement
cout << i << endl;
outputs the new value 3.
You can equivalently rewrite the while loop the following way
while (i < 10)
if (i % 2 == 0)
cout << ++i << endl;
else
++i;

Order of precedence in CPP

In the following code:
#include<iostream>
using namespace std;
int main()
{
int x = 1 , y = 1, z = 1;
cout << ( ++x || ++y && ++z ) << endl; //outputs 1;
cout << x << " " << y << " " << z ; //x = 2 , y = 1 , z = 1;
return 0;
}
According to me, logical AND should evaluate first, followed by logical OR. However, the results seem to be contrasting my assumption. Can someone explain?
The operators || and && are short-circuit (if not overloaded).
Hence, for ||: if the first argument is true, the second is not evaluated.
For &&: if the first is false, the second is not evaluated.
If a in a || (b && c) is true, the second expression isn't evaluated whatever it contains.
(I set parentheses (which are actually not necessary) to emphasize what the 2nd argument of || is.)
operator&& has higher precedence than operator||, that means ++x || ++y && ++z will be interpreted as ++x || (++y && ++z), which doesn't mean (++y && ++z) gets evaluated firstly. ++x is still evaluated firstly, it gives a non-zero value which could convert to bool with value true, then (++y && ++z) won't be evaluated due to short-circuit evaluation.
You seem to be confusing the precedence of an operator with order of evaluation. Yes, && has higher precedence than ||, so ++x || ++y && ++z is evaluated as ++x || (++y && ++z), but it's still evaluated from left to right.
See also Order of evaluation:
Every value computation and side effect of the first (left) argument of the built-in logical AND operator && and the built-in logical OR operator || is sequenced before every value computation and side effect of the second (right) argument.
That is, the left argument of || will always be evaluated before the right argument. Thus ++x is evaluated first, this yields true and the condition short-circuits, so (++y && ++z) isn't evaluated at all.

Explain the following output? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Please explain the output:
#include<iostream.h>
int main()
{
int i= -3, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
OUTPUT :
-2 2 0 1
Here's what I thought:
(++i || ++j) && (++k) //Considering the precedence order
++i becomes -2 so first part of OR true, so it won't check 2nd part.
(Thanks Joachim Pileborg for telling me the short circuit evaluation)
So overall, first part of AND is true.
But that is not enough for statement to be true, 2nd part must be true to.
So ++k makes k = 1
Here's where I get it wrong. Why is k not increasing?
whereas, in this case:
#include<iostream.h>
int main()
{
int i= -1, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
OUTPUT:
0 3 1 1
I got this one too considering short circuit evaluation.
Let's start with this code snippet
#include<iostream.h>
int main()
{
int i= -3, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
It is obvious that m will be have a boolean value converted to int. As ++i is equal to -2 that is unequal to zero then all other expressions will not be evaluated because it is already known that the whole expression is equal to true. So after statement
m = ++i || ++j && ++k;
m is equal to 1 and i is equal to -2 All other variables were not changed.
In this code snippet
#include<iostream.h>
int main()
{
int i= -1, j=2, k=0, m;
m = ++i || ++j && ++k;
cout<< i <<" " << j << " " << k <<" "<<m;
return 0;
}
++i will be equal to 0. So the right operand of operator || will be evaluated. This operand is
++j && ++k
As ++j will be equal to 3 and is not equal to 0 then ++k also will be evaluated and will be equal to 1. As the both operands of operator && is not equal to zero then the result is equal to true
Thus you will get i == 0, j == 3, k == 1, m == 1.
From the C++ Standard
5.14 Logical AND operator
1 The && operator groups left-to-right. The operands are both
contextually converted to bool (Clause 4). The result is true if both
operands are true and false otherwise. Unlike &, && guarantees
left-to-right evaluation: the second operand is not evaluated if the
first operand is false.
5.15 Logical OR operator
1 The || operator groups left-to-right. The operands are both
contextually converted to bool (Clause 4). It returns true if either
of its operands is true, and false otherwise. Unlike |, ||
guarantees left-to-right evaluation; moreover, the second operand is
not evaluated if the first operand evaluates to true.
In logical expressions, such as: ... || ... && ... C++ can omit executing statements that would not change the output value of expression. For example: if it computes first value and it's output is not equal to 0, then expression: true || ... && ... is always true, therefore execution of further expressions is not necessary
Below is your second case:-
int i= -1, j=2, k=0, m;
m = ++i || ++j && ++k;
In
( cond1 || cond2)
expression if cond1 is true then compiler does not go on to check for cond2. It will evaluate cond2 only if cond1 returns false.
So, in second ++i makes first expression to be false and forces compiler to go on to evaluate further whereas in first case first expression returns true.

How does the compiler interpret this expression, in terms of Precedence and Associativity?

It's an exercise from C++ Primer 5th:
Exercise 4.33: Explain what the following expression does(Page158):
someValue ? ++x, ++y : --x, --y
The codes:
bool someVlaue = 1;
int x = 0;
int y = 0;
someVlaue ? ++x, ++y : --x,--y;
std::cout << x << std::endl << y << std::endl;
I tried Gcc4.81 and Clang3.5, both gave me:
1
0
Press <RETURN> to close this window...
Why not 1 and 1? Can anyone explain how it was interpreted?
Because of the very low precedence of the comma operator, the expression
someValue ? ++x, ++y : --x,--y;
is equivalent to:
(someValue ? ++x, ++y : --x),--y;
So the ++x, ++y expression is executed (setting x and y to 1), followed by the expression --y at the end, restoring y to 0.
Note - the comma operator introduces a sequence point, so there is no undefined behavior from modifying y more than once.
The expression
someValue ? ++x, ++y : --x, --y
is evaluated as
(someValue ? ((++x), (++y)) : (--x)), (--y)
As you can see, the y is modified twice, once incremented and once decremented, thus the result is 1 0 and not 1 1.

If-statemenet condition [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a trouble understanding what does this code do :
#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 0;
if (x++ && y++)
y += 2;
cout << x + y << endl;
return 0;
}
The output is 1 by C++. But I think it should be 2?
Why? Because in the () of if statement, I think there should only check if it's true/false, so it doesn't increment/decrement any of the integers. And since that's true by default, it increases y for 2? And output should be 0+2 = 2, but it outputs only 1?
if (x++ && y++) will not do y++ because the condition to the left of the logical and operator (&&) is false since x++ will return 0 and increment x by 1.
Since false && expression will yield false for any expression, there is no need to evaluate the rest of it.
Hence, you end up with x = 1 and y = 0.
This is called Short-circuit Evaluation.
The post ++ operator has high priority and && operator is allowed to short circuit evaluation.
What happens in if (x++ && y++) is that first it evaluates x++. The result is 0 and increments x. Since 0 is false && will short circuit the evaluation of y++ (will not be executed). Also the if will evaluate to false and will not execute the y+=2.
So now you have x=1 and y=0.
So the result is 1.
it will first execute x++ and the compiler knows that because of that the expression x++ && y++ will be false and will ignore y++
as a result after that x = 1 and y = 0;
it is the same as writing if(false && do_something()) , in this case do_something() will never be called.
I advice you to take a look at the operator precedence chart : http://en.cppreference.com/w/cpp/language/operator_precedence
//in a statement, x++ will evaluate x then increment it by 1.
//in a statement, ++x will increment x by 1 then evaluate it.
If you have hard time to understand it then try the below code to better understand :
#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 0;
if (++x && ++y) // in your case, with the previous code, it gives (0 && 0)
// instead of if statement you can try the following : cout << x++; then cout << ++x;
// and notice the difference
y += 2;
cout << x + y << endl;
return 0;
}