Is there a C++ equivalent for C# null coalescing operator? I am doing too many null checks in my code. So was looking for a way to reduce the amount of null code.
There is a GNU GCC extension that allows using ?:
operator with middle operand missing, see Conditionals with Omitted Operands.
The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression.
Therefore, the expression
x ? : y
has the value of
x
if that is nonzero; otherwise, the value ofy
.This example is perfectly equivalent to
x ? x : y
In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.
This extension is also supported by clang. However, you should check with the compiler you're using and portability requirements for your code before using the extension. Notably, MSVC C++ compilers do not support omitted operands in ?:
.
See also related StackOverflow discussion here.