埃尔维斯运算符

编程语言中,埃尔维斯运算符是一种二元运算符,常写为?:or||,如果第一操作数求值为真则返回其值,否则返回第二操作数的值。类似于带有“最后值”语义的短路求值。埃尔维斯运算符是受三元条件运算符 ? :启发而被提出的。因为埃尔维斯运算符表达式A ?: B近似于三元条件运算符A ? A : B

埃尔维斯运算符得名于它的通常表示法?:,相似于埃尔维斯·普雷斯利(即“猫王”)的颜文字侧脸的额发英语quiff,或者其他角度看相遇于他的得意的笑脸。[1]

有一个相似的运算符是空值结合运算符,把布尔真值检查改为是否为空指针null。常写为??,如C#[2]

编程语言支持 编辑

类似的短路运算符OR 编辑

Common Lisp, Clojure, Lua, Object Pascal, Perl, Python, Ruby, JavaScript等编程语言中, OR运算符(典型为||or)都是短路行为:如果左操作数的值为真,则表达式结果为真,不再对右操作数求值。这被称作短路求值

C/C++语言标准强制||&&短路求值运算符。

参见 编辑

参考文献 编辑

  1. ^ Joyce Farrell. Java Programming. 7 February 2013: 276. ISBN 978-1285081953. The new operator is called Elvis operator because it uses a question mark and a colon together (?:); if you view it sideways, it reminds you of Elvis Presley. 
  2. ^ ?? Operator. C# Reference. Microsoft. [5 December 2018]. (原始内容存档于2022-02-07). 
  3. ^ Using the GNU Compiler Collection (GCC): Conditionals. gcc.gnu.org. [2022-03-05]. (原始内容存档于2022-01-12). 
  4. ^ Using and Porting the GNU Compiler Collection (GCC): C Extensions. gcc.gnu.org. [2022-03-05]. (原始内容存档于2021-07-14). 
  5. ^ Elvis Operator (?: ). [2022-03-05]. (原始内容存档于2021-08-16). 
  6. ^ The Apache Groovy programming language - Groovy 1.5 release notes. groovy-lang.org. [2022-03-05]. (原始内容存档于2022-02-11). 
  7. ^ PHP: Comparison Operators - Manual. PHP website. [2014-02-17]. (原始内容存档于2022-02-28). 
  8. ^ Null Safety - Kotlin Programming Language. Kotlin. [2022-03-05]. (原始内容存档于2022-02-13). 
  9. ^ Albahari, Joseph; Albahari, Ben. C# 6.0 in a Nutshell 6. O'Reilly Media. 2015: 59. ISBN 978-1491927069. 
  10. ^ Efftinge, Sven. Xtend - Expressions. eclipse.org. [2022-03-05]. (原始内容存档于2021-05-06). 
  11. ^ Closure Templates - Expressions. GitHub. 29 October 2021 [2022-03-05]. (原始内容存档于2022-03-05). 
  12. ^ The Swift Programming Language (Swift 4.1): Basic Operators. developer.apple.com. [2022-03-05]. (原始内容存档于2017-11-12). 
  13. ^ Elvis Operator - Ballerina Programming Language. Ballerina. [2018-12-19]. (原始内容存档于2018-12-20). 
  14. ^ clojure.core or macro API reference. [2022-03-05]. (原始内容存档于2022-02-25). 
  15. ^ Nullish coalescing operator (??). mozilla. [2021-01-28]. (原始内容存档于2022-02-28) (英语). 
  16. ^ nullish coalescing commit by Kingwl · Pull Request #32883 · microsoft/TypeScript. GitHub. [2019-10-08]. (原始内容存档于2020-11-12) (英语). 
  17. ^ Lua or operator Reference. [2022-03-05]. (原始内容存档于2022-01-30).