conditional operator in Xcode

some tech talk about conditional operator picked from Programming in Objective-c 6th edition


A non-ANSI extension to the syntax of the conditional operator, which is supported by Xcode, is shown here:

condition ?: expression

In this syntax, condition is evaluated, and if true, then the value of the operation is condition. If condition is false, then the value of the operation is expression.Logically, this syntax is identical to the following:

condition ? condition : expression

However, in the former case condition will only be evaluated once, whereas in the latter case

it could be evaluated twice.

Here’s how you could set the value of result to index if it were nonzero, or to -1 otherwise:

result = index ?: -1;


s = ( x < 0 ) ? -1 : x * x;

The condition x < 0 is first tested when the previous statement is executed. Parentheses are generally placed around the condition expression to aid in the statement’s readability. This is usually not required, though, because the precedence of the conditional operator is very low(lower, in fact, than all other operators but the assignment operators and the comma operator).


If the expression after the : (the “else” part) consists of another conditional operator, you

can achieve the effects of an else if clause. For example, the sign function implemented in Program 6.6 can be written in one program line using two conditional operators, as follows:

sign = ( number < 0 ) ? -1 : (( number == 0 ) ? 0 : 1);

If number is less than zero, sign is assigned the value -1; if number is equal to zero, sign is assigned the value 0; otherwise, it is assigned the value 1. The parentheses around the “else” part of the previous expression are actually unnecessary. This is because the conditional opera- tor associates from right to left, meaning that multiple uses of this operator in a single expression, such as in

e1 ? e2 : e3 ? e4 : e5

group from right to left and therefore are evaluated as follows:

e1 ? e2 : ( e3 ? e4 : e5 )

Conditional expressions don’t have to be used on the right side of an assignment; they can be used in any situation in which expressions can be used. This means you can display the sign of the variable number without first assigning it to a variable using an NSLog statement, as shown here:

NSLog (@"Sign = %i", ( number < 0 ) ? -1

: ( number == 0 ) ? 0 : 1);








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值