LearnFrenzy
Sign in Take a free test

Functions and Default Arguments · Functions MCQ · Question 3

Why pass a std::string by const reference? Answer, explanation & discussion

  • MCQ
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Why is void print(const std::string& s) preferred to void print(std::string s)?

  • A It allows modifying s
  • B It avoids copying the string while preventing modification, and still accepts temporaries Correct
  • C It is required for strings
  • D It makes the function inline
Correct Answer: Option B

Copying a long string allocates memory. A const reference reads the caller's string directly and safely.

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