0

I'm new to programming and can't work this out and have looked everywhere i can think for an answer. The if statement in function1 if (m != 0 || 1) doesn't seem to be read when cin >> 1 is passed from function2. Here is my code, any help would be appreciated.

#include <iostream>

void function1(int i);

int main() {
    using namespace std;

    int i;

    function1(i);

return 0;
}
----------------------------------------------------------------------------
#include <iostream>

void function2();

void function1(int i) {
    using namespace std;
    if (i != 0 || 1 ) /* not working when the variable 'i' is passed from function2 */ {     
    cout << endl << "i != 0 || 1" << endl;
    function2();
    }
    else if (i == 0 || 1) {
        if (i == 0) {
            cout << endl << "m == 0" << endl;
        }
        else if (i == 1) {
            cout << endl << "m == 1" << endl;
        }
    }
}
----------------------------------------------------------------------------
#include <iostream>

void function1(int i);

void function2() {
    using namespace std;

    int i;

    cout << endl << "type 0 or 1" << endl;
    cin >> i;    /* type 1 or 0 in here */
    function1(i);
}
martijnn2008
  • 3,552
  • 5
  • 30
  • 40
Richard
  • 23
  • 1
  • 7

2 Answers2

3

Try changing this:

if (i != 0 || 1 )

To this:

if (i != 0 || i != 1 )  
Ethan
  • 1,905
  • 2
  • 21
  • 50
  • No problem. I feel like this code can be trimmed down a lot though. I see you establishing `function1()` with an `int` parameter, but you don't seem to pass anything into it. The function won't be called if you don't explicitly do so from outside with an `int` parameter. – Ethan Jul 24 '16 at 17:33
  • See my edit, I think you're trying to do something like this: – Ethan Jul 24 '16 at 17:33
  • The code you pasted in with your edit is no valid c++. Actually, I don't get myself what you try to explain with it... – Aconcagua Jul 24 '16 at 17:41
  • @Aconcagua you're right. That's what I get for switching languages three times already today. – Ethan Jul 24 '16 at 17:43
3

Although user154248's answer is (in parts at least) correct, you might be interested in why...

The reason is that operator!= has higher precedence (i. e. is evaluated before) operator||. So your if clause is equivalent to if((i != 0) || 1).

Additionally, any value unequal to 0 (null/zero) is evaluated to true, if used in an expresstion expecting a boolean parameter, so you get if((i != 0) || true). And now, what ever i != 0 evaluates to, the overall expression x || true will result in true.

Finally – we are back at user154248's answer...

However, there is a problem left: i != 0 || i != 1 will also always evaluate to true: If i equals 0, i != 1 evaluates to true, if i equals 1, i != 0 does so...

What you actually need is i != 0 && i != 1.

Aconcagua
  • 24,880
  • 4
  • 34
  • 59