Speed = Level > 5 ? 10 : 5;
// 等价于
if (Level > 5)
Speed = 10;
else
Speed = 5;
一些编译器会对三元操作符有优化:
#include <time.h>
int Level = 1;
time_t time1, time2, time3;
int main()
{
int N = 1000000;
time1 = clock();
for (int i=0; i<N; i++)
string rank = Level > 10 ? "Master" : "Beginner";
time2 = clock();
for (int i=0; i<N; i++)
{
string rank1;
if (Level>10)
rank1 = "Master";
else
rank1 = "Beginner";
}
time3 = clock();
cout << time2-time1 << endl;
cout << time3-time2 << endl;
}
不用三元运算符,则先要创建一个空字符串对象,然后用新对象对他覆盖。使用三元运算符并不会构造这个中间字符串,是一种返回值优化,会更快。(这里我使用的是xcode,在试验过程中发现如果N很小的话,三元运算符反而更慢,但N很大就会快很多,可能编译时三元运算符的转化有关,也可能是xcode本身的一些问题。总之,推荐使用三元运算符。)
三元运算符是可以嵌套的,可以简化代码,但不太易懂,不太推荐。