This is a GNU extension on ternary operation according to the Wikipedia.
iMyVal = --iVal ?: iDft;
While I'm fully aware that this is a GNU extension, but sometimes things may come in very handy with this special syntax.
So, does anybody know if this syntax is only available in gcc
? Or are they any other compilers which support it?
to anyone who's interested, PHP started supporting this syntax from 5.3
Thanks in advance.
Some answers:
- GCC - yes
- MSVC - no (based on vanetto's answer)
- CLANG -
no yes - the LLVM online compiler compiles it successfully.
- Intel C compiler - yes
Bottom line - not wide-spread. Only Intel's compiler, which is almost 100% gcc-compatible, supports this.?
C++11 workaround:
template<typename Fcond, typename Flast>
auto ternary2support(Fcond fcond, Flast flast) -> decltype(fcond())
{
auto cond_result= fcond();
return cond_result? cond_result : flast();
}
#define ternary2(c,case0) ternary2support( [&](){ return (c);}, [&](){ return (case0);} )
void test_tern2()
{
int i= 3;
int res1= ternary2(--i,1000);
int res2= ternary2(--i,1000);
int res3= ternary2(--i,1000);
std::cout<<" res1="<< res1<<" res2="<< res2<<" res3="<< res3;
// output: res1=2 res2=1 res3=1000
}
int main(){test_tern2(); return 0;}
Lambda lasyness prevents the condition recalculation and unnecassary case0 expression evaluation (as the original ternary operator extension works)