4 ms·
It does not eliminate the conditional jump, it's just synctatic sugar.
by throwaway744678 5y ago
It does not eliminate the conditional jump, it's just synctatic sugar.
- PixelOfDeath 5y agoUntil after C++11, ternary was the only way to use "if then" in constexpr functions. So it has slightly more use from a C++ point of view.
- gpderetta 5y agoIn a funny turn of events, in C++17 there is no ?: shorthand for 'constexpr if' .
- MaxBarraclough 5y agoFollowing that line, it's never exactly been syntactic sugar. When initializing a const local, you can use the ternary operator on the right hand side of the assignment, but you can't get the same effect using if (short of writing a new function). Similarly, C++ lets you use the ternary operator for the left hand side of an assignment, (a ? b : c) = 42; although you could use an if for this pretty easily.
- andromeduck 5y agoWow I had no idea you could use it on the LHS. TIL.
- MaxBarraclough 5y agoA TIL of my own: it seems not to be allowed in C.
- saagarjha 5y agoIt works if you take the address of the b and c and then dereference. I assume this works without those in C++ because of references.
- TonyTrapp 5y agoAnd to make it more complicated, both "regular" ifs and ternaries may not generate a branch at all, e.g. by using the CMOV (conditional move) instruction on x86. This avoids a branch but can obviously not eliminate the data dependency between the condition and a later consumer of the result.