这个问题已经有了答案:
C conditional operator ('?') with empty second parameter [duplicate]
6个答案
我找到了一种方法来分配这样的值:

NSString *result = [self string] ?: @"none";

如果[self string]返回的值不等于零,则结果将是返回的值,否则为@“none”。就像python中的or操作符一样。
我测试了好几例,效果不错。比如:
int a = 10 ?: 0; // a is 10
int a = 0 ?: 5; // a is 5
NSString *str = @"abc" ?: 10; // warning: incompatible pointer. It has type checking?

但是我找不到任何相关的文档或关于这个语法的信息。所以我想知道它为什么会起作用。有人能解释一下吗?

最佳答案

这是对c的gnu扩展,记录了here。注意,它只对表达式进行一次计算,并重用结果(当表达式有副作用时有用)。CLAN包括它,但我找不到任何相关的文件。
编辑:这里是LLVM实现的类引用:http://clang.llvm.org/doxygen/classclang_1_1BinaryConditionalOperator.html
注意,也就是说:
BinaryConditionalOperator—条件运算符的GNU扩展,允许省略中间操作数。

10-07 19:27
查看更多