Search code examples
c#c++nullnull-coalescing-operator

C# null coalescing operator equivalent for c++


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.


Solution

  • 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;
    }