Why am I always getting 1 as answer irrespective of the value assigned to the variable a

86 Views Asked by At

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 !!
    }
}
2

There are 2 best solutions below

0
On

It is unclear what you are trying to do but the condition in the if statement

if (a = 8  && (a = a - 5))

is equivalent to

if ( a = ( 8  && (a = a - 5 ) ) )

So the logical AND operator yields true because the left operand 8 is not equal to 0 and the right operand that represents the assignment expression a = a - 5 also is not equal to 0. So a is assigned with the bool value true that is in the assignment ( a = true ) converted to 1.

To get the expected result 3 you have to write the condition like

if ( ( a = 8 ) && (a = a - 5))
0
On

in this example because first evaluate 8 && (a = a - 5) which is always true and equal to 1 then it will assign to a that's why it will became 1.

if you see here it will show that first && will evaluate then = which is result became 1 even if you change number.

should write in this order:

if ((a = 8)  && (a = a - 5))