Why am I getting 1 as output instead of 7 ( if a is initially assigned with 12 , then a-5 should give 7) or 3 as ( if a is assigned with 8 then a-5 should give 3 ). The output remains 1 always irrespective of the value assigned to a.
int main()
{
int a = 12;
if (a = 8 && (a = a - 5))
cout << a;
else
{
//do nothing !!
}
}
It is unclear what you are trying to do but the condition in the if statement
is equivalent to
So the logical AND operator yields true because the left operand
8is not equal to0and the right operand that represents the assignment expressiona = a - 5also is not equal to 0. Soais assigned with the bool valuetruethat is in the assignment (a = true) converted to1.To get the expected result 3 you have to write the condition like