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.
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 ? : yhas the value of
xif that is nonzero; otherwise, the value ofy.This example is perfectly equivalent to
x ? x : yIn 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.
Here are two macros to replicate the ?? and ?. operators. These macros ensure:
Example usage:
COA( nullPtr, goodPtr )->sayHello();
COA( nullPtr, COA( nullPtr, goodPtr ) )->sayHello();
COACALL( goodPtr, sayHello() );
COACALL( nullPtr, sayHello() );
COACALL( COA( nullPtr, goodPtr ), sayHello() );
Definitions:
#define COA(a, b) ([&](){ auto val = (a); return ((val) == NULL ? (b) : (val)); }())
#define COACALL(a, b) ([&](){ auto val = (a); if (val) (val->b); }());
Note: COACALL does not return results. Only use with void calls or alter to fit your needs.
Just to add to the answers mentioning the ?: operator (the "Elvis operator"): I sometimes use a helper function together with this operator that gets the underlying value of a pointer or std::optional or similar types that "wrap" a value and have a boolean conversion to indicate the presence of a value. For example:
template <typename T>
constexpr T coalesce (std::optional<T> opt) {
return *opt;
}
template <typename T>
constexpr T coalesce (T fallback) {
return fallback;
}
std::optional<int> opt1{5};
std::optional<int> opt2;
int val1 = coalesce(opt1 ?: 0);
int val2 = coalesce(opt2 ?: 0);
The only drawback is that this must be used carefully and won't give you a static check of correct use. E.g. you could just do coalesce(opt2) without the ?: fallback and that would be the same as doing *opt2 without first checking whether it contains anything. So the name coalesce is sort of misleading, but when used correctly it looks self-explanatory (and pretty neat) in my opinion.