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
+6
A:
There isn't a way to do this by default in C++, but you could write one:
in C# the ?? operator is defined as
a ?? b === (a != null ? a : b)
So, the C++ method would look like
Coalesce(a, b) // put your own types in, or make a template
{
return a != null ? a : b;
}
McKay
2009-11-23 19:34:20
In this method b is evaluated even if a isn't null. This might be a problem if b has side effects.
Amnon
2009-11-23 19:52:16
@Amnon: Indeed. Consider: `p = Coalesce(p, new int(10));`. Also, it seems in C# the right-hand operand cannot be NULL (can't be checked at compile-time, since there are no nullable types in C++?). On the other hand: is there that much need for it in C++, so that you can't just type `a ? a : b;`?
UncleBens
2009-11-23 21:34:01
+2
A:
How about this?
#define IFNULL(a,b) ((a) == null ? (b) : (a))
Justin Grant
2009-11-23 19:34:59
beware of IFNULL(a++, b)Yeah, I realize you'd want to beware of that anyway if you think a might be null.IFNULL(SomeClass.DoSomethingReallyLong(), "")causes problems too.
McKay
2009-11-23 19:40:18
Good point-- serves me right for being lazy. Using a template method is definintely the way to go here, since it avoids side effects and will have equivalent performance (or better). I'm going to add a +1 on @McKay's solution now. :-)
Justin Grant
2009-11-23 20:27:16
A function template doesn't necessarily have equal or better performance. This "short-circuits" (`b` is not evaluated unless `a` is null), whereas a function's arguments are always evaluated.
Steve Jessop
2009-11-23 22:02:09
@Steve Correct Justin's code would "perform" better in the case ofIFNULL("", SomeClass.DoSomethingReallyLong());
McKay
2009-11-23 22:25:18
Also a good point. But, I think the most common use case (at least in C# when I've used the ?? operator) is where a is more expensive (e.g. database call, XML parsing) than b. Often b is a constant, like 0 or "". So I suspect the template would win out most of the time. Plus, unless you know how the macro is implemented, the double-execution wouldn't be obvious to the macro's caller, while function-call semantics are well-known so anyone with an expensive b would know to skip the function and just manually create a temporary variable. Funny, I'm arguing against my own answer... :-)
Justin Grant
2009-11-23 22:37:05
And I was arguing against my own. Both have their advantages and drawbacks.
McKay
2010-10-26 22:52:12