0

Plz help me understand why a is 1?

int a = 7, b = 8; if (a=5 || b==5) cout << a; cout << " " << b;

10th Aug 2020, 3:04 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Respuestas
+ 6
If you will write any number in if condition it will give bool values it will be true or false Same in your case if you will assign any values (not 0) in if statement compiler understood it as bool value so it will be 1 not 5 which u assigned in you program. If u will run this program in different compiler some Compilers will give value of a is 5 and some Compilers will give 5 but it should be 1 not 5 ig u will try in sololearn playground it will show you warning but answer will give 5 not 1 This example will figures out to help you try this program in sololearn #include <iostream> using namespace std; int main() { int a; if(a=5); cout<<a; return 0; } output should be 1 not 5
12th Aug 2020, 12:21 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 5
It was evaluated as follows a = (5 || b == 5) a = (true || false) a = (true) But Playground suggested use of parentheses, not sure why it was considered necessary, but adding parentheses as follows got rid of the warning. if ((a=5 || b==5)) (Edit) Considering logical OR operator only requires one truthy operand to conclude, and the rule of short-circuit evaluation, the RHS, a boolean expression `b == 5` will not be evaluated.
10th Aug 2020, 3:16 PM
Ipang
0
~ swim ~ Considering || has higher precedence over =, what kind of confusion or surprises is waiting ahead? isn't it clear by then which operation is to be performed first? isn't the compiler aware of that well enough? Yes I forgot about the short-circuit evaluation thing.
10th Aug 2020, 11:20 PM
Ipang