LearnFrenzy
Sign in Take a free test

Functions and Default Arguments · Predict the Output · Question 8

Modifying an element through a returned reference Answer, explanation & discussion

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

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

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

int& largest(std::vector<int>& v) {
    int i_max = 0;
    for (int i = 1; i < static_cast<int>(v.size()); ++i)
        if (v[i] > v[i_max]) i_max = i;
    return v[i_max];
}

int main() {
    std::vector<int> v{4, 9, 2, 7};
    largest(v) = 0;
    largest(v) += 100;
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';
    return 0;
}
  • A 4 0 2 107 Correct
  • B 4 109 2 7
  • C 4 100 2 7
  • D 104 0 2 7
Correct Answer: Option A

The function returns a reference to the element itself, so assignments change the vector: 9 becomes 0, then the new largest (7) gets +100.

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