+ 13
C++ - Why a is assigned 1?
Result is 1 1: int a = 7, b = 1; if(a = 8 || b == 5) cout << a*b; cout << " " << a;
9 Respostas
+ 19
Any non zero number is considered true. Short circuit evaluation for logical OR ignores the rest of the expression when the first operand evaluates to true.
a = (8 || b == 5)
a = (true || b == 5) // b == 5 is skipped
a = (true) // true equals to 1
cout << a * b;
// a(1) * b(1) output '1'
cout << " " << a;
// output a space and '1'
+ 8
if(a = 8 || b == 5)
a = true || ( no evaluate because 1st _____________condition true , (1 + 0 = 1))
a = true
true == 1 ( true = 1 and false = 0)
a = 1
+ 7
Why is 5 skipped??
+ 7
Gustav A C/D C âąïž
It is because of short circuit evaluation for the condition/expression in `if` statement. In this case, there is no need to evaluate right-hand side operand (`b == 5`), because left-hand side operand (8, a non zero value) is considered true, and thus is enough to conclude the evaluation result.
A logical OR operator yields true when either one of the operands evaluates to true, in this case the left-hand side operand (8) does evaluate to true, that's why.
https://en.m.wikipedia.org/wiki/Short-circuit_evaluation
+ 7
|| has a higher precedence than =
+ 5
I don't like to start sentences with "Am I the only one who..." but... Am I the only one who sees that there are more than 9000 answers and there are actually 5 answers to this question. I mean yesterday was the same and I thought it was a bug but now (even after update) it's still the same and no one mentioned this bug..
+ 4
voja
No worries, you're not the only one đ
This morning I saw a note from moderator David Carroll (in another thread not here), in response to a call for aid about a spammer who heavily stormed the thread. I think most (if not all) of hot today was stormed.
The spammers just managed to push thousands of spam responses. The spam was gone along with the user's account, but the response counter doesn't seem to be in sync. I guess it just happens with banned user account contents.
+ 4
This is because of the operator precedence. The other expression is evaluated to true that's why a is assigned 1 if it was evaluated to zero then a would have retained a 0 value.