S1r-Lanzelot
S1r-Lanzelot

Reputation: 2266

Evaluating a single char in an if statement: C++

I am having some troubles with my if loop.

First off I have I assigned char sign.

 void evaluate_ps(istream& input) 
 {
    char sign;
    input >> sign;
    cout << sign << endl;
    check(sign);
 }

That prints / so my sign has the value '/'

Then I go to my void check(char operation) function

 void check(char operation)
 {
    if(operation != '-' || operation != '+' ||
      operation != '*' || operation != '/')
       {
       return false;
       }
       else return true;
 }

and it's returning false... WHY!!!! I can't seem to figure this out.

Thanks everyone.

Upvotes: 2

Views: 5816

Answers (3)

DanZimm
DanZimm

Reputation: 2578

The if statement is responding to the / not equaling one of the other values

Think about "or" even in a general sense

if blue is not green or is not red or is not blue say nope

you would need to do something like the following:

if (operation != '+' && operation != '-' && operation != '/' && operation != '*') {
    return false;
}
return true;

this way its like this

if blue is not green and is not red and is not blue say nope

Upvotes: 1

codaddict
codaddict

Reputation: 455400

This happens because you are using the || (OR) operator. When operation is / the check operation != '-' returns true. Since || is short circuited, the entire expression returns true.

Change it to && (AND):

if (operation != '-' && operation != '+' &&
   operation != '*' && operation != '/')

Another way to write this is:

if (!(operation == '-' || operation == '+' ||
      operation == '*' || operation == '/'))

Upvotes: 4

Mysticial
Mysticial

Reputation: 471569

You probably meant all your || to be &&:

if(operation != '-' && operation != '+' && 
  operation != '*' && operation != '/')

Otherwise, it will always enter the if-statement since a character will always not equal one of 4 different things.

Upvotes: 3

Related Questions