LearnFrenzy
Sign in Take a free test

Functions and Default Arguments · Find the Error · Question 9

Error: modifying a const reference parameter Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

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

void shout(const std::string& msg) {
    msg += "!";
    std::cout << msg << '\n';
}

int main() {
    shout("Hello");
    return 0;
}
  • A "Hello" is not a std::string
  • B msg is a const reference, so += cannot modify it; work on a copy or take the parameter by value Correct
  • C shout must return std::string
  • D += does not work on strings
Correct Answer: Option B

Taking std::string msg by value gives the function its own copy to change – a good choice when the function would copy anyway.

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