+10

# 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/18/2019 12:08:21 PM

Paolo De Nictolis

+16

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'

+6

|| has a higher precedence than =

+6

In OR logical operation, if any oneone condition is right whole condition is right . so that ,Answer is 8

+5

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 `b == 5`, because 8 is considered true, and thus is enough to conclude the evaluation result. An OR operator yields true when either of the operands were true, that's why. https://en.m.wikipedia.org/wiki/Short-circuit_evaluation

+4

Why is 5 skipped??

+4

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..

+3

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

+3

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.

+3

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.