grady
grady

Reputation: 12745

C# logic question

I have those boolean values:

bool test = false && true || true; // true
bool test1 = false && (true || true); // false

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)

Upvotes: 0

Views: 777

Answers (9)

Nandha Kumar
Nandha Kumar

Reputation: 126

The order of precedence flows in the following order

  1. ()
  2. &&
  3. ||

Hence in first case && takes over || and insecond case () takes over &&

Upvotes: 0

Khemka
Khemka

Reputation: 108

In the first one && has precedence over || because you have not grouped explicitly.

In the second one, (...) lead to || being evaluated first.

Thus the differing results.

Upvotes: 0

Justin Stryker
Justin Stryker

Reputation: 373

bool test = false && true || true; // true

This first is true because the statement is testing whether the it is true or false.

bool test1 = false && (true || true); // false

The second one if false because the statement is testing whether it is true and false.

Upvotes: 0

Anand Thangappan
Anand Thangappan

Reputation: 3106

First one:

False and True or True

One condition satisfied, So its return true

Second one:

False and (True or True) = False and True

one condition failed, So its return false

Upvotes: 0

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

In your first example false && true is evaluated first and it evaluated as false. Then false OR true is of course evaluated to true.

In your second, because of the () true OR true is evaluated first to true, then true && false is evaluated to false.

So it makes perfectly sense.

Upvotes: 0

Tokk
Tokk

Reputation: 4502

in test you have false && true, which is false and then you have false || true which is true. In the second case you evaluate (true || true) at first => true and then false && true which is false.

Upvotes: 1

detaylor
detaylor

Reputation: 7280

The first evaluates false && true first (false) and then the result with || true, which gives true.

The second evaluates the value in the parenthesis first so true || true and then the result with && false, which gives false

Upvotes: 0

Steve Mayne
Steve Mayne

Reputation: 22818

The && is evaluated first in your first expression - meaning you end up with the result of false || true, rather than false && true in the second expression.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

The && operator has precedence over || meaning that your first expression is equivalent to:

bool test = (false && true) || true;

which gives:

bool test = false || true;

which gives:

bool test = true;

In the second case you are explicitly grouping the operands:

bool test1 = false && (true || true);

which gives:

bool test1 = false && true;

which gives:

bool test1 = false;

Upvotes: 11

Related Questions