Home > Backend Development > PHP Tutorial > What's the Difference Between the `||` and `|` Operators in Programming?

What's the Difference Between the `||` and `|` Operators in Programming?

Susan Sarandon
Release: 2024-12-08 09:28:11
Original
715 people have browsed it

What's the Difference Between the `||` and `|` Operators in Programming?

Using OR Operators in Programming: | vs ||

When working with OR expressions in programming languages like C# and PHP, it's common to use the double pipe (||) operator. However, occasionally, the single pipe (|) is also used. What's the difference between these two operators?

Short-Circuiting Behavior

The double pipe (||) is a "short-circuit" operator. This means that in an OR expression involving multiple conditions, if the first condition evaluates to true, the remaining conditions will not be evaluated.

For example:

if (condition1 || condition2 || condition3)
Copy after login

If condition1 is true, the evaluation stops, and condition2 and condition3 are not checked.

Regular Evaluation

In contrast, the single pipe (|) operator performs regular evaluation. This means that it will always evaluate all the conditions in an OR expression, regardless of the result of the first condition.

if (condition1 | condition2 | condition3)
Copy after login

In this example, all three conditions will be evaluated, even if condition1 is true.

Potential Caveats

While the single pipe (|) operator generally provides better performance, it has one potential caveat. Unlike the short-circuit OR, the regular OR operator does not stop evaluating when it encounters a null reference or similar error.

For example:

if (class != null || class.someVar < 20)
Copy after login

If class is null, the regular OR operator will still try to evaluate class.someVar, resulting in a NullReferenceException.

Bitwise Operations

In addition to their use in OR expressions, the | and & operators can also be used for bitwise operations. In this context, they perform binary operations on the binary representations of their operands.

The above is the detailed content of What's the Difference Between the `||` and `|` Operators in Programming?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template