horin
horin

Reputation: 1662

C++ operators precedence

I am using this statement

if ((pm && pn) || (pm == false && pn == false))

it is supposed to return true only if both pm and pn are true or if both are false. But this is also returning true if only only first one (pm) is true.

So now it is acting like this:

0 0 = 1
0 1 = 0
1 0 = 1
1 1 = 1

but I need it to work like this:

0 0 = 1
0 1 = 0
1 0 = 0
1 1 = 1

can you tell me where am I making mistake?

Upvotes: 0

Views: 175

Answers (6)

Pete Becker
Pete Becker

Reputation: 76245

Since the question's title asks about precedence, note that || has lower precedence than &&. So the two sets of inner parentheses are redundant, and the original expression is just a longer way of saying

if (pm && pm || pm == false && pn == false)

Now, fixing the obvious typo:

if (pm && pn || pm == false && pn == false)

Removing the unneeded explicit comparisons:

if (pm && pn || !pm && !pn)

And, finally, a less obvious transformation, which others have suggested:

if (pm == pn)

Upvotes: 0

Xin
Xin

Reputation: 1330

Why not try xor?

if (!(pm ^ pn)) { /*...*/ }

Or simply equal?

if (pm == pn) { /*...*/ }

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

if ((pm && pm) || (pm == false && pn == false))

it is supposed to return true only if both pm and pn are true or if both are false. But this is also returning true if only only first one (pm) is true.

Because you made a typo. You meant pm && pn.

Instead just write if (pm == pn), which is equivalent along as the only semantic values are indeed true and false for both variables.

Plus, consider making your variable names clearer and more distinct.

Note that operator precedence has nothing to do with this.

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254431

pm && pm

should be

pm && pn
       ^

The whole expression can be simplified to

pm == pn

if the variables already have bool type.

Upvotes: 2

Paul Evans
Paul Evans

Reputation: 27567

What you want is simply:

if (pm == pn)

Upvotes: 4

juanchopanza
juanchopanza

Reputation: 227390

You are checking if pm is true twice. You also need to check if both are the same, not whether they are both true. So,

if ((pm == pn) 
        ^^ ^^

Upvotes: 2

Related Questions