LearnFrenzy
Sign in Take a free test

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

decltype versus auto for references Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

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

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

int main() {
    std::vector<int> v{1, 2, 3};
    auto a = v[0];                 // int
    decltype(v[0]) b = v[1];       // int& – decltype keeps the reference
    decltype(auto) c = v[2];       // int& as well
    int n = 5;
    decltype(n) d = n;             // int (declared type of the name)
    decltype((n)) e = n;           // int& – parenthesised expression is an lvalue
    a = 10; b = 20; c = 30; d = 40; e = 50;
    std::cout << v[0] << ' ' << v[1] << ' ' << v[2] << ' ' << n << ' ' << std::is_reference_v<decltype(b)> << '\n';
    return 0;
}
  • A 1 20 30 50 1 Correct
  • B 10 20 30 40 1
  • C 1 2 3 5 0
  • D 1 20 30 40 1
Correct Answer: Option A

auto copies; decltype of an expression like v[0] keeps the reference; decltype(n) is int but decltype((n)) is int&, so e refers to n.

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