CPP Syntax Fundamentals & Data Structures 2 — Questions and Answers
Question 1: What is the output of the following code? ```cpp int x = 5; std::cout << x++ << " " << ++x; ```
- 5 7 (Correct answer)
- 6 7
- 5 6
- 6 6
Correct answer: 5 7
x++ returns 5 (post-increment), then ++x increments to 7 and returns 7, giving '5 7'.
Question 2: Which container provides O(1) average-case lookup by key in C++ STL?
- std::map
- std::unordered_map (Correct answer)
- std::set
- std::vector
Correct answer: std::unordered_map
std::unordered_map uses a hash table, giving O(1) average-case lookup, unlike std::map which is O(log n).
Question 3: What does the following declaration create? ```cpp int* const ptr = &x; ```
- A pointer to a constant integer
- A constant pointer to an integer (Correct answer)
- A constant pointer to a constant integer
- A null pointer
Correct answer: A constant pointer to an integer
int* const ptr declares a constant pointer (the pointer itself cannot be reassigned) to a non-const integer.
Question 4: Which C++ standard introduced the range-based for loop?
- C++03
- C++11 (Correct answer)
- C++14
- C++17
Correct answer: C++11
The range-based for loop (for (auto x : container)) was introduced in C++11.
Question 5: What is the size of an empty class in C++?
- 0 bytes
- 1 byte (Correct answer)
- 4 bytes
- It is undefined
Correct answer: 1 byte
C++ guarantees that every object has a unique address, so an empty class has size 1 byte.
Question 6: Which of the following correctly initializes a std::vector with five zeros?
- std::vector<int> v(5); (Correct answer)
- std::vector<int> v = {5};
- std::vector<int> v[5];
- std::vector<int> v(5, 0, 0);
Correct answer: std::vector<int> v(5);
std::vector<int> v(5) constructs a vector of 5 elements, all value-initialized to 0.
Question 7: What is the difference between 'struct' and 'class' in C++?
- struct cannot have member functions
- struct members are public by default; class members are private by default (Correct answer)
- struct does not support inheritance
- struct and class are completely identical
Correct answer: struct members are public by default; class members are private by default
The only default difference is access: struct defaults to public, class defaults to private for both members and inheritance.
What is the output of the following code?
```cpp
int x = 5;
std::cout << x++ << " " << ++x;
```