0

In javascript I can write the following:

const bar = getBar();
const foo = bar || 0;

If getBar() returns a null value, foo will fallback to 0.

In C++ I could do this:

auto bar = getBar();
int foo = bar? bar: 0;

But is there a more concise way of doing this in C++?

Toivo Säwén
  • 1,905
  • 2
  • 17
  • 33
  • as written the second line is the same as `int foo = bar;`. Only if `bar == 0` you assign `0` instead of `bar`s value. Did you actually mean `int foo = bar ? *bar : 0;` ? – 463035818_is_not_an_ai Apr 19 '21 at 13:20
  • You can write your own `or_null` function to do this. – François Andrieux Apr 19 '21 at 13:21
  • 3
    It will depend on the type `getBar()` returns. – MikeCAT Apr 19 '21 at 13:21
  • What is the purpose of `foo`? How will it be used? What problem is it supposed to solve that isn't possible by checking `bar` directly? – Some programmer dude Apr 19 '21 at 13:22
  • Also remember that C++ doesn't have the concept of null "values", though they can be emulated using e.g. `std::optional` or pointers. – Some programmer dude Apr 19 '21 at 13:24
  • 2
    g++ and clang have a language extension, where you can omit the "true" case and it returns the value of the condition: ```int foo = bar ?: 0;``` but it's intended for cases where the true case is expensive to compute or is a long expression and you don't want to duplicate it. – Chris Uzdavinis Apr 19 '21 at 13:24
  • 1
    Understanding the question very strictly, `int foo = getBar();` is the answer. If `getBar()` returns a "null" value and the return type is compatible with `int` as your solution suggests, then `foo` will be assigned `0`. – nielsen Apr 19 '21 at 13:25
  • `Foo* p = GetFoo(); int i = p ? p->GetValue() : 0;` or `std::optional x = GetOptInt(); int i = x ? *x : 0;` – Eljay Apr 19 '21 at 13:43

0 Answers0