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"; }
}- A. iX
- B. R
- C. iR
- 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
- What is printed? cpp int main() { map<string, int> m; if (m["x"] == 0) cout << m.size(); cout << m.count("y") << m.size(); }
- What is printed? cpp int main() { set<int, greater<int>> s{3, 1, 3, 2}; for (int x : s) cout << x; cout << s.size(); }
- What is printed? cpp int main() { vector<int> v{1, 2, 3, 2, 4}; v.erase(remove(v.begin(), v.end(), 2), v.end()); cout << v.size() << ":"…
- What is wrong with this loop? cpp vector<int> v{1, 2, 3}; for (int x : v) if (x == 1) v.pushback(1);
- What is printed? cpp void log(int) { cout << "G"; } struct S { void log() { cout << "M"; } void run() { log(5); } }; int main() { S s…
- What happens (C++14)? cpp struct S { static int n; }; int main() { S::n = 1; cout << S::n; }