LearnFrenzy
Sign in Take a free test

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

auto, auto& and range-for over a vector Answer, explanation & discussion

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

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

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

int main() {
    std::vector<int> v{1, 2, 3};
    for (auto x : v) x *= 10;
    for (auto& x : v) x += 1;
    auto first = v[0];
    auto& last = v[2];
    first = 100;
    last = 300;
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';
    return 0;
}
  • A 2 3 300 Correct
  • B 11 21 31
  • C 100 3 300
  • D 20 30 300
Correct Answer: Option A

auto copies, auto& refers. The first loop and the first variable change copies; only the auto& ones touch the vector.

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