-1

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 ?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Why do you think it is going into the `else` block ? Did you debug it ? – wohlstad Jan 16 '23 at 10:06
  • 1
    For me it prints `3` which is the value of `a` after the assignment `a = 3`, i.e. the `if` is executed, not the `else`. – wohlstad Jan 16 '23 at 10:07
  • 3
    This isn't a temporary change. This is an ordinary assignment at an unusual place. – moooeeeep Jan 16 '23 at 10:07
  • 3
    fwiw, you cannot learn a language from google. try here https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – 463035818_is_not_an_ai Jan 16 '23 at 10:08
  • 1
    The code will go in the "if" scope and print the value "3", not the "else" scope. – GhostVaibhav Jan 16 '23 at 10:09
  • [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jesper Juhl Jan 16 '23 at 10:42
  • A conditional can't change a value temporarily. You either found some questionable source or misunderstood what it said. (Or found something relating to an entirely different language.) – molbdnilo Jan 16 '23 at 10:55
  • Change the `else` block to `cout << "else";` and you will see that it doesn't execute. (You carefully chose your values so the program has the same output for both branches if it *isn't* the case that the variable changes temporarily.) – molbdnilo Jan 16 '23 at 10:59

1 Answers1

5

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 )
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335