Initializers in if

Initializers in if

Sergey Abbakumov

In C++, you can declare variables that are converted to bool, directly in parentheses of the if operator:

if (bool is_enabled = IsEnabled())
  assert(is_enabled);

while (bool should_contunue = ShouldContinue())
  assert(should_continue);

if (void* ptr = GetPointer())
  assert(ptr != nullptr);

if (std::optional<int> value = GetOptional())
  assert(value.has_value());


In C++17, initializers were introduced directly into the operator:

if (Status status = Foo(); !status.ok())
  return status;


What strongly reminds Go:

if err := Foo(); err != nil {
  return err
}

Telegram channel: https://t.me/sea_plus_plus

Report Page