LearnFrenzy
Sign in Take a free test

Functions and Default Arguments · Predict the Output · Question 18

A function returning std::optional Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 18 Back to Exercise

What is the output of the following C++ program?

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

std::optional<int> parse_digit(char c) {
    if (c >= '0' && c <= '9') return c - '0';
    return std::nullopt;
}

int main() {
    std::string s = "a7b3";
    int sum = 0, bad = 0;
    for (char c : s) {
        if (auto d = parse_digit(c)) sum += *d;
        else ++bad;
    }
    std::cout << sum << ' ' << bad << ' ' << parse_digit('x').value_or(-1) << '\n';
    return 0;
}
  • A 10 2 -1 Correct
  • B 73 2 -1
  • C 10 2 0
  • D 10 4 -1
Correct Answer: Option A

Digits give a value (7 + 3 = 10); letters give an empty optional, which is false in the if. value_or supplies a fallback for an empty optional.

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