how to compiler compile if statement [duplicate] - c++

This question already has answers here:
Is Short Circuit Evaluation guaranteed In C++ as it is in Java?
(2 answers)
Closed 9 years ago.
main()
{
int k = 5;
if(++k <5 && k++/5 || ++k<=8); // how to compiler compile this statement
print f("%d",k);
}
// Here answer is 7 but why ?

++k < 5 evaluates to false (6 < 5 = false), so the RHS of the && operator is not evaluated (as the result is already known to be false). ++k <= 8 is then evaluated (7 <= 8 = true), so the result of the complete expression is true, and k has been incremented twice, making its final value 7.
Note that && and || are short circuit boolean operators - if the result of the expression can be determined by the left hand argument then the right hand argument is not evaluated.
Note also that, unlike most operators, short circuit operators define sequence points within an expression, which makes it legitimate in the example above to modify k more than once in the same expression (in general this is not permitted without intervening sequence points and results in Undefined Behaviour).

Unlike many questions like this, it appears to me that your code actually has defined behavior.
Both && and || impose sequence points. More specifically, they first evaluate their left operand. Then there's a sequence point1. Then (if and only if necessary to determine the result) they evaluate their right operand.
It's probably also worth mentioning that due to the relative precedence of && and ||, the expression: if(++k <5 && k++/5 || ++k<=8) is equivalent to: if((++k <5 && k++/5) || ++k<=8).
So, let's take things one step at a time:
int k = 5;
if(++k <5 &&
So, first it evaluates this much. This increments k, so its value becomes 6. Then it compares to see if that's less than 5, which obviously produces false.
k++/5
Since the previous result was false, this operand is not evaluated (because false && <anything> still always produces false as the result).
|| ++k<=8);
So, when execution gets to here, it has false || <something>. Since the result of false | x is x, it needs to evaluate the right operand to get the correct result. Therefore, it evaluates ++k again, so k is incremented to 7. It then compares the result to 8, and finds that (obviously) 7 is less than or equal to 8 -- therefore, the null statement following the if is executed (though, being a null statement, it does nothing).
So, after the if statement, k has been incremented twice, so it's 7.
In C++11, the phrase "sequence point" has been replaced with phrases like "sequenced before", as in: "If the second expression is evaluated, every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second expression." Ultimately, the effect is the same though.

In following:
for && "something" is evaluated when first condition is True
for || "something" is evaluated when first condition is False
( (++k <5) && (k++/5) ) || (++k<=8)
( 6 < 5 AND something ) OR something
( False AND something ) OR something
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
False OR 7 < 8
False OR True
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
True
So k comes out to be 7

Initially k is assigned 5, in your declaration, then in following if condition:
++k < 5 && k++ / 5 || ++k <= 8
// ^
// evaluates
Increments k to 6 then its and LHS of && operand evaluates false.
6 < 5 && k++ / 5 || ++k <= 8
// ^ ^^^^^^^
// 0 not evaluates
Then because of Short-Circuit behavior of && operator k++ / 5 will not evaluates.
Short-Circuit behavior of && operator is:
0 && any_expression == 0, so any_expression not need to evaluate.
So above step 2 conditional expression becomes:
0 || ++k <= 8
// ^^^^^^^^
// evaluates
Increments k to 7 then its:
0 || 7 <= 8
because you have ; after if, so no matter whether if condition will evaluates True or False printf() will be called with k = 7.

Related

C++ Boolean with Integers

OK so obviously this question might sound dumb for more experienced people, but, for the following lines the result I get is 0:
int x = 2,
y = -2;
cout << (x++ - y && (--x + y));
I understand it means that either one of these two expressions equals 0, but how? As far as I understand, this should be (3 && -1)?
Also, a little subquestion: when does x++ exactly take effect? On the next occurance of x within the same expression, after the left-shift operator within the same line, or in the next statement?
Thank you!
As far as I understand, this should be (3 && -1)?
you understand wrong:
first left side is fully evaluated, as it is necessary for short circuit evaluation with logical and (details can be found here)
x++ - y == 4 // as result of x++ == 2 so (2-(-2)), after that x == 3
result is true so right side is evaluated:
--x + y == 0 // as result of --x == 2 so (2+(-2)), after that x == 2
result on the right is false so result of and is false as well which printed by std::ostream as 0
Note: short circuit evaluation of logical or and and operations make such code valid (making them sequenced) but you better avoid such questionable expressions. For example simple replacing logical and to binary would make it UB.

Operator Precedence

I have a sample midterm question that I am not too sure about. Here it is:
#include <iostream.h>
void f( int i )
{
if( i = 4 || i = 5 ) return;
cout << "hello world\n" ;
}
int main()
{
f( 3 );
f( 4 );
f( 5 );
return 0;
}
So I understand that the logical OR operator has a higher precedence and that it is read left to right. I also understand that what's being used is an assignment operator instead of the relational operator. I just dont get how to make sense of it all. The first thing the compiler would check would be 4 || i? How is that evaluated and what happens after that?
Let's add all the implied parentheses (remembering that || has higher precedence than = and that = is right-associative):
i = ((4 || i) = 5)
So, it first evaluates 4 || i, which evaluates to true (actually, it even ignores i, since 4 is true and || short-circuits). It then tries to assign 5 to this, which errors out.
As written, the code doesn't compile, since operator precedence means it's i = ((4 || i) = 5) or something, and you can't assign to a temporary value like (4 || i).
If the operations are supposed to be assignment = rather than comparison == for some reason, and the assignment expressions are supposed to be the operands of ||, then you'd need parentheses
(i = 4) || (i = 5)
As you say, the result of i=4 is 4 (or, more exactly, an lvalue referring to i, which now has the value 4). That's used in a boolean context, so it's converted to bool by comparing it with zero: zero would become false, and any other value becomes true.
Since the first operand of || is true, the second isn't evaluated, and the overall result is true. So i is left with the value 4, then the function returns. The program won't print anything, whatever values you pass to the function.
It would make rather more sense using comparison operations
i == 4 || i == 5
meaning the function would only print something when the argument is neither 4 nor 5; so it would just print once in your example, for f(3).
Note that <iostream.h> hasn't been a standard header for decades. You're being taught an obsolete version of the language, using some extremely dubious code. You should get yourself a good book and stop wasting time on this course.
The compiler shall isuue an error because expression 4 || i is not a lvalue and may not be assigned.
As for the expression itself then the value of it is always equal to true because 4 is not equal to zero.

Why does the compiler skip some parts of a compound statement [duplicate]

This question already has answers here:
Shortcircuiting of AND in case of increment / decrement operator
(6 answers)
Closed 8 years ago.
For example in the code below
int x,y,z;
x=y=z=1;
z = ++x && ++y || ++z;
cout<<x<<y<<z;
The output is 2 2 1.
I guess it is because compiler knew that '++x && ++y' gives a 'true', so it skipped the remaining line || ++z.
However, if I replace it with the code below:
z = ++x && ++y && ++z;
the output is still 2 2 1.
shouldn't it be 2 2 2, because all parts of ANDs '++x' , '++y' , '++z' has to be evaluated.
I guess it is because compiler knew that '++x && ++y' gives a 'true', so it skipped the remaining line '|| ++z'.
That's correct. It's not necessarily done at compile time though, it could be performed at run time in a more complex situation (as the compiler can't guarantee to know the values within each variable.
That's not why z == 1 though.
You're setting z = ++x && ++y && ++z, which implicitly casts the boolean produced by the && to an integer. The integer representation of the boolean true is 1, therefore z == 1.

AND and OR operator [duplicate]

This question already has an answer here:
Short circuit behavior of logical expressions in C in this example
(1 answer)
Closed 7 years ago.
Aren't the individual expressions in a composite logical AND/OR expression supposed to be evaluated first before the logical operators are applied to their result?Why is ++k untouched in the condition m = ++i && ++j || ++k for the following program :
#include<stdio.h>
int main()
{
int i=-3, j=2, k=0, m;
m = ++i && ++j || ++k;
printf("%d, %d, %d, %d\n", i, j, k, m);
return 0;
}
Output : -2,3,0,1
But I expect the output -2,3,1,1
You should avoid coding such unreadable code. It is actually parsed as
m = (++i && ++j) || ++k;
So once j >= 0 the ++j condition is always true, so ++k is not evaluated since && is a short-cutting and then but || is a short-cutting or else (so they may not evaluate their right operand).
So && is evaluated as follow: the left operand is evaluated, if it is false it is returned, and then only when it is true (i.e. not equal to 0) the right operand is evaluated and returned as the evaluated result of the &&. Likewise || is evaluated as follow: the left operand is evaluated. If it is true (non-zero) it becomes the result of the ||; or else the right operand is evaluated and is the result of the || expression.
In particular, when coding if (x > 0 && 20/x < 5) the division is never attempted for x==0 .
Read also the wikipedia operators in C & C++ & short circuit evaluation & lazy evaluation pages; and please take several hours to read a good C programming book.
Logical operators have short circuit evaluation, i.e. as soon as a value is determined for the expression, the rest of the expression is not evaluated.
e.g. m = ++i && ++j || ++k;
in this ++i -> true, ++j -> true (non zero value)
hence m = true && true || ++k;
now true && true is true
so
m = true || ++k
As in OR operator if 1 side is true, the other is not evaluated so result is true.
Hence k is not incremented.
That is a shortcut for logical operators, in your case operator ||. When the first operand is true, it's impossible for the second operand to have any impact on the result. It will always be true, not matter what the second operand may yield. So the second operand is not evaluated.
The same goes for the logical && operator, if the first operand is found to be false. The second operand will not matter, the result will always be false and the second operand will therefor not be evaluated.
&& and || are logical operators, and you are using them out of context which is odd (ok for C/C++ but you'd have type errors in Java or C#).
You've have just discovered short circuiting operators - you don't need to evaluate the whole expression if you "know" it's true. i.e. i and j are non zero so you don't need to do anything with k since you know the expression is true.
m = ++i && ++j || ++k;
Above line of code executes ++i and ++j first and doesn't execute ++k since it's written after || (OR)
Logical Circuit Operators don't execute when previously statement is true already in case of || and false in case of &&
Hence k is untouched

What is the difference between && and ||? [duplicate]

This question already has answers here:
Is short-circuiting logical operators mandated? And evaluation order?
(7 answers)
Closed 8 years ago.
I'm getting it difficult to understand how the following programs work, kindly help me in understanding.
int x=2,y=0;
(i)
if(x++ && y++)
cout<<x<<y;
Output:
(ii)
if(y++ || x++)
cout<<x<<" "<<y;
Output: 3 1
(iii)
if(x++||y++)
cout<<x<<" "<<y;
Output: 3 0
Kindly explain me how the program is working and also, what makes the difference between (ii) and (iii).
You are looking at a "C++ puzzle" which is using two languages tricks.
The first is that postincrement uses the value of the variable first, then increments the variable.
So x++ has the value 2 in the expression and then x becomes 3
y++ has the value 0 in the expression, and then y becomes 1
&& is and
|| is or
both operators are short-circuiting.
Look at && first.
In order for and to be true, both sides must be true (non-zero)
Since it is x++ && y++, first the x++ happens, and since it is non-zero (true)
the y++ has to happen to determine whether the result is true or not.
Therefore x is 3 and y is 1.
The second case is the same. y is zero, but in order to determine if the OR is true,
the if statement executes the second half of the expression.
The third case, since it is in the opposite order, never executes y++ because
x++ || y++
the first half being x++, it is already true, so the compiler does not bother to execute the second half of the test.
int x=2,y=0;
Condition in if() is evaluated according to the rules:
operator && evaluates left operand first and if the value is logically false then it avoids evaluating the right operand. Typical use is for example if (x > 0 && k/x < limit) ... that avoids division by zero problems.
operator || evaluates left operand first and if the value is logically true then it avoids evaluating the right operand. For example if (overwrite_files || confirm("File existing, overwrite?")) ... will not ask confirmation when the flag overwrite_files is set.
To understand the following it is also important to note that x++ is postincrementation what means that in if( x++) x has the old value but just in the next line (or even same line but after if() was tested) x is incremented.
(i)
if(x++ && y++) // x=2,y=0;
// 2 so y++ is evaluated
cout<<x<<y; // skipped, but now x=3,y=1;
Output:
(ii)
if(y++ || x++) // x=2,y=0;
//0 so x++ is evaluated
cout<<x<<" "<<y; // x=3,y=1;
Output: 3 1
(iii)
if(x++||y++) // x=2,y=0;
//2 so y++ is not evaluated
cout<<x<<" "<<y; // x= 3,y=0;
"IF" argument evaluation order?
In C++ (and a few other languages) && and || are your logical operators in conditions. && is the logical AND operator and || is the logical OR operator.
When using these in a condition, the result of the condition is dependent on what is on either side of these operators and is read as if you were just saying the words.
Example:
if(thisNum > 0 && thisNum < 10) is read as "if thisNum is greater-than zero AND less-than 10, the condition will be true." Therefore, any number between 0 and 10 will make the condition true.
if(thisNum > 0 || thisNum < 10) is read as "if thisNum is greater-than zero OR less-than 10, the condition will be true." Therefore, ANY number at all will make this statement true because only one part of this statement has to be true to evaluate to TRUE.
A more detailed explanation on how these work is this:
OR (||) - If EITHER or BOTH sides of the operator is true, the result will be true.
AND (&&) - If BOTH and ONLY BOTH sides of the operator are true, the result will be true. Otherwise, it will be false.
There are many more explanations, including truth tables around the internet if you do a Google search to assist in understanding these.
As for your examples.
if(x++ && y++)
cout<<x<<y;
You are doing an if statement that is comparing the the values of x and y. The important thing to remember is that you are NOT comparing the values together. In C++, and non-zero value will evaluate to TRUE while a zero value will result in FALSE. So, here you are checking to see if x AND y are TRUE and then increasing their values by one AFTER the comparison. Since x = 2 and y = 0, we have one TRUE value and one FALSE value and since we have a && (AND) operator between them we know the result of the condition is FALSE (since both aren't TRUE) and the output is skipped.
if(y++ || x++)
cout<<x<<" "<<y;
In this example, we are doing the same thing EXCEPT we are doing a logical OR operation instead of AND (since we have || and not &&). This means, as I said above, that only one part of the condition has to be TRUE to result in TRUE. Since our values are still x = 2 and y = 0, we have one TRUE value and one FALSE value. Since part is TRUE, the whole condition is TRUE and the output occurs.
The reason the result is 3 1 and not 2 0 is because of the ++ operators after the variables. When the ++ operators are after the variable, it will add one AFTER the rest of the line has occurred and done the actions it needs. So it does evaluates the condition THEN increases the values by one.
if(x++||y++)
cout<<x<<" "<<y;
This example is EXACTLY the same, the only difference is that the values have been swapped. And since it is an OR (||) operation, only one part has to be TRUE. And as before, we have one TRUE value (since x is non-zero) and one FALSE value (since y is zero). Therefore, we have a TRUE result, meaning the output is NOT skipped and we get the answer 3 1 again (since the ++ operators came AFTER the variables).
Now, speaking of the ++ operator. What if in the first example it had been:
if(++x && ++y)
cout<<x<<y;
We would get a DIFFERENT result in this situation. Since the ++ operator comes BEFORE the variables, the first thing that happens is that the values are increased by one AND THEN the condition is evaluated. Since our new values would be x = 3 (TRUE) and y = 1 (also TRUE), we can conclude that we would get the same result as the other two examples since BOTH values are TRUE (which, since we have an AND (&&) operator, BOTH variables have to be TRUE to result in TRUE).
Hope this helps.
EDIT:
One of the other answers made an excellent point about the second and third examples. Result wise, there is no difference. HOWEVER, in terms of how it is evaluated there is a difference.
C++ automatically does something called "short-circuit evaluation". This means, it will skip any evaluations if it knows the result is already going to be TRUE or FALSE. This means that with an OR operation, if the first part is TRUE it will just skip the second part since it already knows the result HAS TO BE TRUE. (Remember, with OR only one part of the comparison has to be TRUE.) So this means that IF the first part is FALSE then the program HAS TO evaluate the second part too, since it determines whether the result will be TRUE or FALSE.
With an AND operation, it will do the opposite. If the first part is FALSE then the program knows the result has to be FALSE and will skip the rest. However, if the first part is TRUE then the program HAS TO evaluate the rest to determine if the result is TRUE or FALSE.
In terms of your examples, this means the second one HAS TO evaluation both sides since the first part results in FALSE.
In the third example, the second part is skipped because the first part is TRUE, meaning the whole condition is TRUE.
For or(||) operator, if the expression of left side is true, it will ignore the expression of right side.
For and(&&) operator, if the expression of left side is false, it will ignore the expression of right side.
This is the answer of your question what makes the difference between (ii) and (iii).
In the output (ii), it is:
as the time where compiler is evaluating y, y is equal to 0 so the statement is false it s evaluating the other member x which is equal to 2 so the statement is true. And then it operates the increment operator.
In the output (iii), it is:
as the time where compiler is evaluating x, x is equal to 2 so the statement is true as the operator of the condition is || it won't evaluate the other expression so the y++ is ignored. Only x will be incremented.