How wide-spread is this GNU extension on ternary operation?

丶灬走出姿态 提交于 2019-12-01 09:56:03

问题


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.


回答1:


Some answers:

  1. GCC - yes
  2. MSVC - no (based on vanetto's answer)
  3. CLANG - no yes - the LLVM online compiler compiles it successfully.
  4. Intel C compiler - yes

Bottom line - not wide-spread. Only Intel's compiler, which is almost 100% gcc-compatible, supports this.?




回答2:


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)



来源:https://stackoverflow.com/questions/12420144/how-wide-spread-is-this-gnu-extension-on-ternary-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!