This question already has an answer here:
The output of cout << 1 && 0;
(1 answer)
Closed 4 years ago.
#include <iostream>
using namespace std;
int main()
{
int a = 8;
cout << "ANDing integer 'a' with 'true' :" << a && true;
return 0;
}
Why does this program output 8 and not 1 (for true)?
If you look at operator precedence, you will find that the left-shift operator << has a higher precedence than the logical AND operator &&.
As such, it is evaluated as:
(cout << "ANDing integer 'a' with 'true' :" << a) && true;
which prints 8.
The logical AND operator, &&, works with expressions.
The first expression is evaluated.
If the first expression is false, no more evaluations.
Otherwise the second expression is evaluated.
Next, the result of the two Boolean expressions is returned.
So, the first expression is evaluated:
cout << "ANDing integer 'a' with 'true' :" << a
A side effect of the evaluation is the following output to the console:
ANDing integer 'a' with 'true' :8
Your output is generated because it is a side-effect of evaluating the first expression.
In the expression 8 && true 8 is evaluated first (and in this turn also streamed). Than true is evaluated and the operator returns true after that. But than the 8 is already in the stream. If you put (8 && true) instead, the parentheses are evaluated first and the result is guarantreed to be 1, which then is streamed.
This behavior is called Operator Precedence - which describes the order in which the operators are executed (in your case && and <<).
The logical AND operator && works with expressions. If both are true returns true and false if otherwise.
cout << "ANDing integer 'a' with 'true' :" << a && true;
is being evaluated as:
(cout << "ANDing integer 'a' with 'true' :" << a) && true;
due to operator precedence (<< having higher precedence than AND &&)
giving you the print of: 8
if we do the following change: (a && true);
it will give you the print of: 1
Related
In short I am getting different output for string comparison using string::compare() vs relational operator '<' on std::string class objects.
string str = "100";
cout << str.compare("10")<<endl; //prints 1
cout << ("100" < "10") <<endl; //prints 1
Here's the demo url
lexicographically "100" is greater than "10" and hence ("100" <"10") must print 0 since it's false but the output 1 i.e true is not expected.
The str.compare() function returns > 0 which is expected validating "100" > "10".
Why is this happening?
In this statement
cout << ("100" < "10") <<endl;
you are comparing two pointers of the type const char * to which the used string literals are implicitly converted. The result of such a comparison is undefined (At least in the C Standard there is explicitly stated that such operation is undefined).
In fact the above statement is equivalent to
cout << ( &"100"[0] < &"10"[0] ) <<endl;
If you want to compare strings the you need to write at least like
cout << (std::string( "100" ) < "10") <<endl;
In this case the output will be
0
Pay attention to that according to the C++ 20 (7.6.9 Relational operators)
...The comparison is deprecated if both operands were of array type prior to these conversions
And the both string literals prior to comparison have array types.
This question already has an answer here:
The output of cout << 1 && 0;
(1 answer)
Closed 7 months ago.
Consider:
int i = 56, j = 0;
int n = i&&j;
cout << i&&j;
cout << endl << n;
whose output would be:
56
0
I imagine it's either because of operator precedence or logical short circuit, but I can't seem to figure out which, or the reason.
The expression cout << i&&j is equivalent to (cout << i) && j. Both operands are evaluated and converted to bool. The statement as a whole has no effect, but the evaluation of the subexpression cout << i has the usual side effects, of course, namely writing something to the standard output.
The && operator is indeed short-circuited and j is only evaluated if cout << i evaluates as true. This condition is equivalent to cout.good(), which is usually the case (unless you somehow managed to close your standard output).
As you expected, the << operator comes takes precedence over &&.
Thus, cout << i&&j first outputs i, then compares the returned stream to j (both are true, so the returned value is true, but this value is discarded).
See here for the full list of operator precedence.
From this page, I got to know that operator precedence of Bitwise AND is higher than Logical OR.
However, the following program gives an unexpected output.
#include<iostream>
using namespace std;
int main()
{
int a = 1;
int b = 2;
int c = 4;
if ( a++ || b++ & c++)
{
cout <<a <<" " << b <<" " << c <<" " <<endl;
}
return 0;
}
The output is
2 2 4
This means that logical OR works first. Does this mean that the operator precedence rule is violated here?
Precedence just means that the expression is written as below
( (a++ || (b++ & c++)))
Once you do that, short circuiting means that just the first expression is evaluated.
This is why a = 2 but b and c are unchanged.
codepad
this link can help you :
http://en.cppreference.com/w/cpp/language/operator_precedence
precedence
10 & Bitwise AND
11 ^ Bitwise XOR (exclusive or)
12 | Bitwise OR (inclusive or)
13 && Logical AND
14 || Logical OR
this means that '&' is evaluated before '||'.
It's perfectly fine to learn about the precedence of these operators, just out of curiosity. In real life, this code without parentheses to make the intent absolutely clear is just unacceptable.
If the left side of an || has a non-zero value, then the right side isn't evaluated at all. It's guaranteed to be not evaluated.
What's happening here?
#include <iostream>
using namespace std;
int main(){
int x=0,y=0;
true? ++x, ++y : --x, --y;
cout << "x: " << x << endl;
cout << "y: " << y << endl; //why does y=0 here?
x=0,y=0;
false ? ++x, ++y : --x, --y;
cout << "x: " << x << endl;
cout << "y: " << y << endl;
}
x: 1
y: 0
x: -1
y: -1
The second case seems fine. I would expect both x and y to increment to 1 in the first case but only the left hand operand increments.
The first one is equivalent to:
(true ? (++x, ++y) : (--x)), --y;
The second one is equivalent to:
(false ? (++x, ++y) : (--x)), --y;
Thus the --y is always executed. In the first line, the increments are executed first so x = 1, y = 0 is expected. In the second line, the decrement of x is executed first so x = -1, y = -1 is expected.
As noted in a comment (to another answer) by Barmar:
And in case anyone is wondering why the comma between ++x and ++y doesn't have the same effect, it's because (true? ++x) would not be valid at all. So the compiler keeps scanning until it finds the :, but beyond that it stops when it reaches a lower precedence operator [(, in this example) or the end of statement].
The y is zero because comma has the lowest precedence among all C++ operators. Because its precedence is lower than that of the ternary conditional operator, the conditional operators are parsed as true? ++x, ++y : --x and false? ++x, ++y : --x. In both cases, the --y statement is executed unconditionally.
EDIT The first comma is different because the compiler has found a ?, so now it needs a : to complete the "when true" expression of the conditional. That is why both ++x and ++y are taken in.
Read the standard
§5.18 Comma operator [expr.comma]
¶1 The comma operator groups left-to-right.
expression:
assignment-expression
expression , assignment-expression
A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discardedvalue
expression (Clause 5).83 Every value computation and side effect associated with the left expression
is sequenced before every value computation and side effect associated with the right expression. The type
and value of the result are the type and value of the right operand; the result is of the same value category
as its right operand, and is a bit-field if its right operand is a glvalue and a bit-field.
¶2 In contexts where comma is given a special meaning, [ Example: in lists of arguments to functions (5.2.2)
and lists of initializers (8.5) —end example ] the comma operator as described in Clause 5 can appear only
in parentheses. [ Example:
f(a, (t=3, t+2), c);
has three arguments, the second of which has the value 5. —end example ]
During work over a simple project I have found situation that I don't fully understand. Consider following code:
#include <iostream>
using namespace std;
bool test(int k)
{
cout << "start " << k << endl;
bool result; // it is important that result's value is opposite to initial value of recheck in main()
result = false;
return result;
}
int main()
{
bool recheck;
recheck = true;
for (int i = 2; i > -1; i--)
{
recheck = (recheck || test(i)); // (1)
cout << i << " ???" <<endl;
}
cout << "----------------------------" << endl;
cout << endl;
recheck = true;
for (int i = 2; i > -1; i--)
{
recheck = (test(i) || recheck); //different order that in (1)
cout << i << "???" <<endl;
}
return 0;
}
It returns completely different results from for loops:
2 ???
1 ???
0 ???
----------------------------
start 2
2???
start 1
1???
start 0
0???
It seems that it first one test(int k) is not even invoked. I suspect it has something to do with || operator. Could anybody explain such a behavior?
The built-in || short-circuits: if the left operand is true, the right operand is not evaluated (it doesn't matter what the value of the right operand is, because the value of the || expression is guaranteed to be true in this case).
For completeness, but not particularly relevant to the question: In c++, the || operator is overloadable, just as many other operators are. If an overload is used, short circuiting does not take place.
The boolean operators || and && will short-circuit when one of the operands - evaluating from left-to-right - can determine the result of the expression, without reference to the remaining operands.
In the case of ||, this means that if the first operand is true, the remaining operands aren't evaluated, because the result of the entire expression will always be true.
In the first loop, the variable recheck - that is local to main - is always true, and so the function call test never needs to be evaluated: it is skipped, and you see no output.
In the second loop, the test function call is evaluated first, and it's result can only be determined after calling the function, so the function is called on each iteration, and you see the output.
Your comment says:
it is important that result's value is opposite to initial value of recheck in main()
Your test() function currently can't see the value of recheck, which is local to main().
Assuming your comment reflects your intent, you need to pass recheck as a parameter to test(); you can then use the unary ! operator, something like:
result = ! recheck;
And of course you need to fix the logic in main() so that test() is called when you need it to be.
Your requirements aren't clear enough for me to comment further.
Others have addressed the specific issue that you have raised. Just a note to say that beware of using multiple question marks in a row. Trigraph sequences start with two '??' characters and the third character after two question marks is interpreted differently.