/*std::optional is a C++17 library feature that provides a convenient way to handle
optional values, i.e., values that may or may not be present. It's essentially a
type-safe variant that can either contain a value or not.

Here's an example to demonstrate how to use std::optional:*/

#include <iostream>
#include <optional>

#if 0
int main() {
  std::optional<int> maybe_value;
  if (!maybe_value) {
    std::cout << "No value\n";
  }

  maybe_value = 42;
  if (maybe_value) {
    std::cout << "Value: " << *maybe_value << '\n';
  }

  maybe_value.reset();
  if (!maybe_value) {
    std::cout << "No value\n";
  }

  return 0;
}
#endif

std::optional<int> divide(int a, int b) {
    if (b == 0) {
        return {};  // return an empty optional
    }
    return a / b;
}

int main() {
    auto result = divide(10, 2);
    if (result) {
        std::cout << *result << std::endl;  // prints 5
    } else {
        std::cout << "division by zero" << std::endl;
    }
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: