【问题标题】:Does the shorthand ternary operator make multiple calculations?速记三元运算符是否进行多次计算?
【发布时间】:2012-07-24 17:18:13
【问题描述】:

三元运算符有一个简写版本,即

var = exp ?: exp2

我知道它适用于 PHP。其他语言可能也采用了它。 C# 具有类似的功能(对于这个问题的上下文)-??

当条件通过时,是重新计算表达式,还是将结果存储在某个地方?

【问题讨论】:

  • 等等,问题是关于什么语言的?

标签: ternary-operator conditional-operator


【解决方案1】:

http://msdn.microsoft.com/en-us/library/ms173224.aspx

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

它被存储,而不是计算两次。

【讨论】:

  • 没错,我想它不应该被比较。原来提到的运营商呢?
  • 然而在 PHP 中,表达式每次都会被计算,例如: php -r "echo rand(0, 1) ?: -999;"这将多次打印 -999。那是因为 expr1 ?: expr2 返回 expr1 而不是表达式的结果。
  • 你似乎自相矛盾,你写它返回 expr1,但打印 -999?
猜你喜欢
  • 2012-02-11
  • 2021-10-06
  • 1970-01-01
  • 2012-08-08
  • 2022-01-24
  • 2013-02-06
  • 1970-01-01
  • 2019-10-08
相关资源
最近更新 更多