37 Ternary Operators in C++
The ternary operator is essentially a ?
and a :
, which is just syntactic sugar for an if statement.
1. General Usage
is equivalent toSimilarly,
std::string rank = s_Level > 10 ? "Master" : "Beginner";
/* ------------------------ */
std::string otherRank;
if (s_Level > 10)
otherRank = "Master";
else
otherRank = "Beginner";
The code here is different from the above, and technically, it is slower because you create a temporary string and then immediately destroy it. The reason why the ternary operator here does not construct an intermediate string is actually related to return value optimization (an advanced compiler feature, which is an optimization technique), which will be discussed later.
For now, just know that writing code this way is cleaner, and in my opinion, it will also be faster.