Why is ‘|’ used as the OR operator in so many programming languages

terminology

The Vertical Bar Operator (|) is used in a variety of constants to mean OR in some way:

C-style languages use a | b to mean bitwise OR of a and b, a || b to mean logical OR of a and b.

Regular expressions use a|b to mean match with a or match with b.

Context Free Grammars use x := a | b in much the same sense as regexes.

While &for AND makes sense, why is | used for OR?

Best Answer

A very good answer is provided on Stack Overflow.

The core of the explanation is:

In Backus-Naur form, an expression consists of sequences of symbols and/or sequences separated by '|', indicating a choice, the whole being a possible substitution for the symbol on the left.

<personal-name> ::= <name> | <initial>

Of course, the next question could be (tnx, @Rob):

"Why is a vertical bar used as the OR operator in Backus-Naur?"

But that is another question, with a merit in itself :)

My assumed answer: because they had to use something, and nothing that was available could be used non-ambiguously.

  • / is the division symbol, path separator in *nix systems

  • \ (today it is path separator in DOS / MS Windows systems)

  • +-* are standard mathematical operators

and so on...


From a comment from @amon:

Backus introduced the grammar notation in The Syntax and Semantics of the Proposed International Algebraic Language where he just used the word "or". Backus et al with Naur as editor replaced this with the symbol "|" in their Revised Report on Algol 60 (original report 1960, revised report 1962) with no explicit reason, probably for brevity. All of this predates Unix by roughly a decade, and slightly predates the ASCII standard.