Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C: Ternary Operator with Omitted Operand

📅 2012-Mar-16 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ c++, gcc, ternary operator ⬩ 📚 Archive

The gcc compiler supports an alternate syntax of the ternary operator:

x = a ? : b;

This is called a ternary operator with omitted operand. This is shorthand for:

x = a;
if ( !x )
    x = b;

This is almost like, but is not like:

x = a ? a : b;

The difference is that a might be a function with side effect. This alternate syntax of the ternary operator ensures that a is processed only once (and not twice like in the second version).

This extension does not seem to be supported in the Visual C++ compilers.