Varaibles Values In If Conditons C++

71 views Asked by At

i am just learning c++ programming language and stuck at some point will anyone help me out. the problem is i had google some stuff and came to know that if conditions can change the varaibles value for temporary basis. my code is below.

#include <iostream>

using namespace std;

int main()
{
    int a = 2;
    int b = a + 1;

    if ((a = 3) == b)
    {
        cout << a;
    }
    else
    {
        cout << a + 1;
    }
    return 0;
}

in the above code its printing the else block why not the if block the conditions must be true ?

1

There are 1 answers

0
Vlad from Moscow On

You are mistaken.

If you will change your code the following way

    int a = 2;
    int b = a + 1;

    if (( a = 3 ) == b)
    {
        std::cout << "if " << a << '\n';
    }
    else
    {
        std::cout << "else " << a + 1 << '\n';;
    }

then you will see the output

if 3

In the expression of the if statement

    if (( a = 3 ) == b)

the left operand of the equality operator is evaluated. As a result a becomes equal to 3 and in turn is equal to b.

If your compiler supports the C++ 17 Standard then you could declare the variables inside the if statement like

if ( int a = 2, b = a + 1; ( a = 3 ) == b )