1

If I have an if statement separated by || returns true, will it continue the statement?

for example: if(true || random()), will random() be executed? because there is no reason for that.

  • 1
    You should really look this type of stuff up first. See here: https://msdn.microsoft.com/en-us/library/6373h346.aspx – sr28 May 17 '16 at 15:55

2 Answers2

5

random() will not be executed:

The conditional-OR operator (||) performs a logical-OR of its bool operands. If the first operand evaluates to true, the second operand isn't evaluated. If the first operand evaluates to false, the second operator determines whether the OR expression as a whole evaluates to true or false.

See || Operator (C# Reference) and this answer.

Community
  • 1
  • 1
Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
  • Is this answer valid for most new languages or only for c#? –  May 17 '16 at 16:09
  • 1
    Really depends on the language. VB (and VB.NET) do not, by default, do short-circuit evaluation (but do them when `And`/`Or` is replaced with `AndAlso`/`OrElse` – Anton Gogolev May 17 '16 at 16:11
1

No, random() will not be executed if you put || and your first condition is true.

However, with | both conditions get checked no matter what the first result is.

Keiwan
  • 8,031
  • 5
  • 36
  • 49