LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Predict the Output · Question 3

std::optional with value_or and has_value Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <optional>
#include <string>
#include <vector>

std::optional<std::string> find_email(const std::string& user) {
    if (user == "asha") return "asha@learn.in";
    return std::nullopt;
}

int main() {
    for (std::string u : {"asha", "ravi"}) {
        auto e = find_email(u);
        std::cout << e.has_value() << ':' << e.value_or("none") << ' ';
    }
    std::optional<int> o;
    o = 5;
    o.reset();
    std::cout << o.has_value() << '\n';
    return 0;
}
  • A 1:asha@learn.in 0:none 0 Correct
  • B 1:asha@learn.in 0: 0
  • C 1:asha@learn.in 0:none 1
  • D 0:none 0:none 0
Correct Answer: Option A

value_or supplies a default for an empty optional; reset() empties it again.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links