-5

I don't understand how "if statement with OR " works.

#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
int main(){
    ios_base::sync_with_stdio(false); 
    cin.tie(NULL);
    cout.tie(NULL);

    char a = ')';

    if(a=='('|| '{') cout<< "true";
    else cout<<"false";

    return 0;

}

My first thought was that the result would be "false" but the program prints "true"

Not a real meerkat
  • 5,604
  • 1
  • 24
  • 55
Cho
  • 9
  • 2
  • 1
    `if(a=='('|| '{')` should be `if (a == '(' || a == '{')` – Jesper Juhl Mar 20 '20 at 14:48
  • You need to compare to `a` both times. – drescherjm Mar 20 '20 at 14:49
  • ***My first thought was that the result would be "false" but my COMPUTER says "true"*** that is because '{' is not zero so true. See what happens when you do this: `if ('{') std::cout << "Got Here" << std::endl;` – drescherjm Mar 20 '20 at 14:52
  • 3
    Does this answer your question? [If always returns true](https://stackoverflow.com/questions/32035762/if-always-returns-true) (Granted, that one deals with strings, not characters, but the idea/takeaway is the same.) – Isaiah Mar 20 '20 at 14:54

2 Answers2

3

What you have is essentially:

if(a=='(')
    cout<< "true";
else if('{')
    cout<< "true";
else cout<<"false";

So the first check is false, then the second check sees if '{' evaluates to true. My c++ is a little rusty, but I believe it will interpret anything other than false or 0 as true.

Kevin
  • 7,162
  • 11
  • 46
  • 70
2
if(a=='('|| '{') cout<< "true";

You have two problems with that statement.


1. Operator precedence

Your condition is not like this:

a == ('(' || '{')

…but like this:

(a == '(') || '{'

2. How operators work

But, even if it were like the first one, that's just not how boolean operators work.

Although it is common in English (and other human languages) to say things like:

if X is Y or Z...

… that is not quite how boolean logic works.

Your approach would be parsed more like this:

if X-is-Y, or Z...

And something like (a == '(') is going to give you a boolean, then OR that boolean with '{'. Not what you intended at all: a character like '{' is always "truthy", and anything OR'd with true is true, so that whole condition will always result in true.

What you need is:

if X-is-Y, or X-is-Z

To accomplish this, rewrite your condition like this:

a == '(' || a == '{'
Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35