var*_*ard 1 c ternary-operator
如果我只使用unsigned三元运算符条件中的类型,这些unsigned变量会自动转换为signed类型吗?
简单的例子:
unsigned int prevTickSeconds = 48;
unsigned int currentTickSeconds = 5;
unsigned int secondsLeft = (currentTickSeconds - prevTickSeconds ) ?
currentTickSeconds - prevTickSeconds :
60 - prevTickSeconds + currentTickSeconds;
Run Code Online (Sandbox Code Playgroud)
(currentTickSeconds > prevTickSeconds)如本例所示,这种结构是否可以正常工作?是否会为三元运算符中的条件自动执行类型转换?
不,没有这样的转换,因为所有类型unsigned int都会出现"下溢".
注意:
60 - prevTickSeconds + currentTickSeconds
Run Code Online (Sandbox Code Playgroud)
将被执行当且仅当currentTickSeconds - prevTickSeconds是0.