ProgrammingModerateProduct-company placement · C++

What is printed?

What is printed?
int main() {
    string s = "hi";
    try { cout << s.at(1); s.at(5); cout << "X"; }
    catch (const out_of_range&) { cout << "R"; }
}
  1. A. iX
  2. B. R
  3. C. iR
  4. D. hR

Correct answer: C. iR

at() checks bounds: index 1 is 'i', index 5 is past the end, so it throws std::out_of_range before X is printed. operator[] would not check (undefined behaviour).

More OOP with C++ and Java questions

Exams that ask this topic