Search code examples
c++if-statementoperand

c++ Reading both left AND right if statement conditions


how do I get the compiler to check both the left and right side of the statement? if I'm not mistaken, i think in C language, it reads both left and right if you have && or || .... so when I looked this up for C++, it says only checks if the left is true....what I need is to be able to check if both sides are true.

so:

//Transactions has been initialized to 0

1. if deposit OR withdraw are greater than or equal to 1, add 1 to variable transactions.
2. if deposit AND withdraw are BOTH greater than or equal 1, then add 2 to variable transactions.
3. else if BOTH are less than 1, transaction is 0.

    if (deposit >= 1 || withdraw >=1)
        {
            transactions = transactions + 1;
            cout << "Transactions:  " << transactions << endl;
        }

    else if (deposit >= 1 && withdraw >=1)
        {
           transactions = transactions + 2;
           cout << "Transactions:  " << transactions << endl;
        }
    else
        {
            cout <<"Transactions: " << transactions << endl;
        }

this issue I'm having is, it reads the left side only, and so transactions only returns 1.

Thank you for your time!

EDIT

https://ideone.com/S66lXi (account.cpp)

https://ideone.com/NtwW85 (main.cpp)


Solution

  • Put the && conditional first and then the || conditional as the else if.

    An explanation, courtesy of zenith (+1 him in the comments if this helps you):

    The most restrictive case needs to go first, since if A && B is true, A || B will always be true anyway. And thus if you put && after ||, the || case will catch whenever the && case is true.

    Also, another side note: leave the cout outside of all the brackets and you can remove the else. It's getting printed no matter what so no need to type it 3 times.