LearnFrenzy
Sign in Take a free test

std::string · Predict the Output · Question 7

Changing characters with [] and a reference loop Answer, explanation & discussion

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

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

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

int main() {
    std::string s = "hello";
    s[0] = 'j';
    s.back() = 'y';
    for (char& c : s)
        if (c == 'l') c = 'L';
    std::cout << s << '\n';
    return 0;
}
  • A jeLLy Correct
  • B jelly
  • C hello
  • D JeLLy
Correct Answer: Option A

[] and back() return references to the characters, and the loop uses char&, so every change modifies s.

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