C++ Arrays / Lists - MCQs

1 min read

1. What is an array in C++?

a) A dynamic data structure that can change size automatically
b) A collection of elements of the same type placed in contiguous memory locations
c) A function that stores multiple variables
d) A collection of elements of different types
Correct Answer: b) A collection of elements of the same type placed in contiguous memory locations
Explanation:
In C++, a standard array is a fixed-size sequence of elements of the same data type stored in contiguous memory blocks.

2. Which of the following correctly declares an integer array of size 5 in C++?

a) int arr(5);
b) int arr[5];
c) array<int, 5> arr();
d) int arr = {5};
Correct Answer: b) int arr[5];
Explanation:
The syntax to declare a built-in array in C++ is type name[size]; therefore, int arr[5]; is the correct declaration.

3. What is the index of the first element in a C++ array?

a) 1
b) 0
c) -1
d) Depends on the compiler
Correct Answer: b) 0
Explanation:
Arrays in C++ are zero-indexed, meaning the first element is accessed using the index 0.

4. What happens if you access an array out of its bounds in C++?

a) The compiler throws a syntax error
b) The program automatically resizes the array
c) It results in undefined behavior
d) It returns a default value of 0
Correct Answer: c) It results in undefined behavior
Explanation:
C++ does not perform bounds checking on built-in arrays. Accessing memory outside the array bounds leads to undefined behavior, which may cause crashes or data corruption.

5. Which of the following initializes all elements of an integer array to zero?

a) int arr[5] = {0};
b) int arr[5] = {1};
c) int arr[5] = 0;
d) int arr[5](https://www.google.com/search?q=0);
Correct Answer: a) int arr[5] = {0};
Explanation:
Initializing an array with {0} sets the first element to 0 and value-initializes the rest to 0 as well.

6. How can you determine the number of elements in a standard C++ array named 'arr'?

a) arr.length()
b) sizeof(arr) / sizeof(arr[0])
c) arr.size()
d) length(arr)
Correct Answer: b) sizeof(arr) / sizeof(arr[0])
Explanation:
For a statically allocated array, sizeof(arr) gives the total bytes, and dividing by sizeof(arr[0]) gives the total number of elements.

7. When passing a built-in array to a function, what is actually passed?

a) A copy of the entire array
b) A pointer to the first element of the array
c) A reference to the array
d) The size of the array
Correct Answer: b) A pointer to the first element of the array
Explanation:
By default, an array decays into a pointer pointing to its first element when passed as an argument to a function.

8. Which of the following statements about C++ array sizes is true?

a) The size must be a constant expression evaluated at compile time
b) The size can be changed during runtime
c) The size is implicitly infinite
d) The size can be omitted in a declaration without initialization
Correct Answer: a) The size must be a constant expression evaluated at compile time
Explanation:
For statically allocated arrays in C++, the array size must be a compile-time constant expression.

9. What is the output of sizeof() when applied to a dynamic array pointer (e.g., int* ptr = new int[10];)?

a) The size of the entire array (40 bytes on 32-bit)
b) The size of the pointer itself (e.g., 4 or 8 bytes)
c) The number of elements in the array (10)
d) 0
Correct Answer: b) The size of the pointer itself (e.g., 4 or 8 bytes)
Explanation:
When sizeof() is applied to a pointer, it returns the size of the pointer, not the memory dynamically allocated to it.

10. What does the declaration 'int arr[] = {1, 2, 3};' do?

a) Causes a compilation error because the size is missing
b) Declares an array of size 3 initialized with 1, 2, and 3
c) Declares an array of size 4 to include a null terminator
d) Creates a dynamically sized array
Correct Answer: b) Declares an array of size 3 initialized with 1, 2, and 3
Explanation:
If the size is omitted, the compiler deduces the size of the array based on the number of elements in the initializer list.

11. Which of the following accesses the third element of the array 'arr'?

a) arr[3]
b) arr[2]
c) arr(3)
d) arr.at(3)
Correct Answer: b) arr[2]
Explanation:
Because arrays are zero-indexed, the first element is at index 0, the second at 1, and the third at index 2.

12. What is array decay in C++?

a) The process of an array losing its size information when passed to a function
b) The destruction of an array at the end of its scope
c) Memory corruption caused by buffer overflow
d) Converting a multi-dimensional array to a 1D array
Correct Answer: a) The process of an array losing its size information when passed to a function
Explanation:
Array decay occurs when an array type implicitly converts to a pointer to its first element, losing its length information.

13. How do you dynamically allocate an array of 10 integers in C++?

a) int arr = new int(10);
b) int* arr = new int[10];
c) int arr[10] = new int;
d) int* arr = alloc(10, int);
Correct Answer: b) int* arr = new int[10];
Explanation:
The 'new' operator followed by the type and size in square brackets is used to allocate a dynamic array.

14. How must you deallocate memory allocated with 'new int[10]'?

a) delete arr;
b) delete[] arr;
c) free(arr);
d) dealloc arr;
Correct Answer: b) delete[] arr;
Explanation:
Dynamic arrays allocated with new[] must be deallocated using delete[] to ensure proper destruction and memory release.

15. In a 2D array declared as 'int matrix[3][4];', what does the '4' represent?

a) The number of rows
b) The number of columns
c) The total number of elements
d) The size of each element in bytes
Correct Answer: b) The number of columns
Explanation:
In a 2D array declaration type name[rows][columns], the second dimension specifies the number of columns.

16. How are 2D arrays stored in memory in C++?

a) Column-major order
b) Row-major order
c) Random scattered blocks
d) As an array of pointers
Correct Answer: b) Row-major order
Explanation:
C++ stores multidimensional arrays in row-major order, meaning elements of the same row are stored contiguously in memory.

17. Which header file is required to use std::array?

a)
b)
c)
d)
Correct Answer: c)
Explanation:
The std::array container is defined in the header file.

18. What is a primary advantage of std::array over built-in C-style arrays?

a) It can change its size dynamically at runtime
b) It supports assignment semantics and knows its own size
c) It consumes less memory than a C-style array
d) It allows elements of different data types
Correct Answer: b) It supports assignment semantics and knows its own size
Explanation:
std::array provides a member function size() and does not decay to a pointer, making it safer. It also supports direct assignment.

19. How do you declare a std::array of 5 integers?

a) std::array arr[5];
b) std::array<int, 5> arr;
c) std::array<5, int> arr;
d) array(int, 5) arr;
Correct Answer: b) std::array<int, 5> arr;
Explanation:
The syntax for std::array specifies the type followed by the constant size inside the template brackets: std::array.

20. Which std::array member function accesses an element with bounds checking?

a) operator[]
b) at()
c) get()
d) value()
Correct Answer: b) at()
Explanation:
The at() function performs bounds checking and throws a std::out_of_range exception if the index is invalid. operator[] does not check bounds.

21. What does the front() method return for an array?

a) An iterator to the first element
b) A reference to the first element
c) A pointer to the first element
d) A copy of the first element
Correct Answer: b) A reference to the first element
Explanation:
The front() method returns a reference to the first element in the container (array, list, vector, etc.).

22. What is the equivalent of a doubly linked list in the C++ Standard Template Library (STL)?

a) std::vector
b) std::deque
c) std::list
d) std::forward_list
Correct Answer: c) std::list
Explanation:
std::list is implemented as a doubly linked list, allowing fast insertions and deletions from anywhere in the container.

23. Which header is required to use std::list?

a)
b)
c)
d) <forward_list>
Correct Answer: b)
Explanation:
To use the std::list container in C++, the header must be included.

24. Which of the following operations has O(1) time complexity in std::list but O(N) in std::vector?

a) Accessing the nth element
b) Inserting an element in the middle (if an iterator is provided)
c) Adding an element to the end
d) Sorting the container
Correct Answer: b) Inserting an element in the middle (if an iterator is provided)
Explanation:
Inserting an element into a list with a known iterator takes O(1) time since it only involves changing pointers, whereas a vector requires shifting elements, taking O(N) time.

25. Does std::list support random access via the [] operator?

a) Yes, for any element
b) Yes, but only for the first and last elements
c) No, it does not support random access
d) Yes, but it is extremely slow
Correct Answer: c) No, it does not support random access
Explanation:
std::list does not support random access (operator[]) because finding an element requires traversing the list from the beginning or end.

26. Which container is a singly linked list in C++?

a) std::list
b) std::vector
c) std::deque
d) std::forward_list
Correct Answer: d) std::forward_list
Explanation:
std::forward_list (introduced in C++11) is implemented as a singly linked list, which is more memory efficient than std::list.

27. What is the primary advantage of std::forward_list over std::list?

a) It supports random access
b) It is faster for push_back operations
c) It has lower memory overhead per node
d) It can be iterated in reverse
Correct Answer: c) It has lower memory overhead per node
Explanation:
std::forward_list uses only one pointer (next) per node instead of two (prev and next) used by std::list, thus saving memory.

28. Which of the following functions is available in std::list but NOT in std::forward_list?

a) push_front()
b) push_back()
c) pop_front()
d) clear()
Correct Answer: b) push_back()
Explanation:
std::forward_list does not have push_back() or back() because traversing to the end of a singly linked list to append takes O(N) time without a tail pointer.

29. How do you insert a node after a specific iterator in a std::forward_list?

a) insert()
b) insert_after()
c) push_after()
d) add()
Correct Answer: b) insert_after()
Explanation:
Because a singly linked list only has forward pointers, inserting at a position requires knowing the previous node, so insert_after() is used instead of insert().

30. Which of the following methods removes all elements from a std::list?

a) erase_all()
b) delete_all()
c) clear()
d) empty()
Correct Answer: c) clear()
Explanation:
The clear() method is standard across STL containers for removing all elements.

31. What does the empty() function of std::list do?

a) Removes all elements
b) Checks if the list has no elements
c) Fills the list with zeroes
d) Deallocates list memory completely
Correct Answer: b) Checks if the list has no elements
Explanation:
The empty() function returns a boolean true if the container is empty, and false otherwise.

32. How do you combine two sorted std::list containers into one sorted list?

a) Using the append() method
b) Using the combine() method
c) Using the merge() method
d) Using the + operator
Correct Answer: c) Using the merge() method
Explanation:
The merge() method merges another sorted list into the calling list, resulting in a single sorted list. The elements from the argument list are moved, not copied.

33. What does the std::list::splice() function do?

a) It splits a list into two equal halves
b) It transfers elements from one list to another without copying or allocating new memory
c) It deletes a range of elements from the list
d) It reverses the list elements
Correct Answer: b) It transfers elements from one list to another without copying or allocating new memory
Explanation:
splice() moves elements between lists by just relinking pointers, making it an O(1) operation (for moving specific elements) without any memory allocation.

34. Which iterators does std::list provide?

a) Random access iterators
b) Bidirectional iterators
c) Forward iterators only
d) Input iterators only
Correct Answer: b) Bidirectional iterators
Explanation:
Because it is a doubly linked list, std::list provides bidirectional iterators allowing iteration forward and backward, but not random access.

35. Which iterators does std::forward_list provide?

a) Bidirectional iterators
b) Random access iterators
c) Forward iterators
d) Output iterators only
Correct Answer: c) Forward iterators
Explanation:
std::forward_list only supports iterating sequentially from the beginning to the end, thus providing forward iterators.

36. What will std::list::remove(val) do?

a) Removes the first occurrence of val
b) Removes all occurrences of val
c) Removes the element at index val
d) Throws an error if val is not found
Correct Answer: b) Removes all occurrences of val
Explanation:
The remove() function scans the entire list and removes all elements that match the given value.

37. If you need to sort a std::list, how should you do it?

a) Using std::sort(list.begin(), list.end())
b) Using list.sort()
c) Using std::stable_sort(list.begin(), list.end())
d) Lists cannot be sorted
Correct Answer: b) Using list.sort()
Explanation:
std::sort requires random access iterators, which std::list does not have. Therefore, std::list provides its own member function sort().

38. What is the time complexity of finding the size of a std::list in C++11 and later?

a) O(N)
b) O(log N)
c) O(1)
d) O(N^2)
Correct Answer: c) O(1)
Explanation:
Since C++11, the standard mandates that std::list::size() must have a constant time complexity, O(1), by maintaining an internal size counter.

39. Does std::forward_list have a size() method?

a) Yes, it operates in O(1) time
b) Yes, it operates in O(N) time
c) No, it does not provide a size() method
d) Yes, but only if explicitly enabled
Correct Answer: c) No, it does not provide a size() method
Explanation:
std::forward_list deliberately omits the size() method to avoid the overhead of storing a size counter, ensuring it remains as lightweight as a raw C singly linked list.

40. How do you count elements in a std::forward_list if size() is not available?

a) std::distance(flist.begin(), flist.end())
b) flist.length()
c) sizeof(flist)
d) flist.count()
Correct Answer: a) std::distance(flist.begin(), flist.end())
Explanation:
You can use std::distance() from the header to count the elements, though it will take O(N) time.

41. What does the reverse() method do in std::list?

a) Sorts the list in descending order
b) Reverses the order of the elements in the list
c) Returns a reverse iterator
d) Inverts the values of all elements
Correct Answer: b) Reverses the order of the elements in the list
Explanation:
The reverse() member function flips the sequence of elements in the list.

42. Which list operation is most efficient at removing duplicate adjacent elements?

a) remove()
b) erase()
c) unique()
d) distinct()
Correct Answer: c) unique()
Explanation:
The unique() function in std::list removes consecutive duplicate elements, leaving only the first of each.

43. If you want unique() to remove all duplicates in a std::list, what must you do first?

a) Call reverse()
b) Call sort()
c) Call clear()
d) Call remove()
Correct Answer: b) Call sort()
Explanation:
unique() only removes *adjacent* duplicates. To remove all duplicates, the list must be sorted first so all identical elements are adjacent.

44. What happens to iterators when an element is inserted into a std::list?

a) All iterators are invalidated
b) Iterators pointing to elements after the insertion are invalidated
c) Iterators pointing to elements before the insertion are invalidated
d) No iterators are invalidated
Correct Answer: d) No iterators are invalidated
Explanation:
Unlike vectors, inserting into a list only involves updating pointers. Existing nodes stay at their memory addresses, so iterators remain valid.

45. What happens to iterators when an element is erased from a std::list?

a) Only the iterator pointing to the erased element is invalidated
b) All iterators are invalidated
c) Iterators pointing to subsequent elements are invalidated
d) No iterators are invalidated
Correct Answer: a) Only the iterator pointing to the erased element is invalidated
Explanation:
Erasing a node frees that node's memory. Iterators pointing to other nodes are entirely unaffected.

46. Which of the following creates a 2D array dynamically?

a) int* arr2D = new int[5][5];
b) int arr2D = new int*[rows]; for(int i=0; i<rows; ++i) arr2D[i] = new int[cols];
c) int arr2D[][] = new int[rows][cols];
d) int arr2D = new int[rows, cols];
Correct Answer: b) int arr2D = new int*[rows]; for(int i=0; i<rows; ++i) arr2D[i] = new int[cols];
Explanation:
A dynamic 2D array is typically created as an array of pointers, where each pointer is initialized with a dynamically allocated row array.

47. When passing a multidimensional array (e.g., int arr[3][4]) to a function, what must be specified in the parameter list?

a) All dimensions
b) None of the dimensions
c) All dimensions except the first
d) Only the first dimension
Correct Answer: c) All dimensions except the first
Explanation:
The compiler needs to know the sizes of all secondary dimensions to calculate pointer offsets properly (e.g., void func(int arr[][4])). The first dimension can be omitted.

48. Which function allows you to get a pointer to the underlying array used by std::array?

a) data()
b) ptr()
c) get()
d) underlying()
Correct Answer: a) data()
Explanation:
The data() method returns a direct pointer to the memory array used internally by std::array.

49. How are elements initialized in std::array<int, 5> arr; if no initializer is provided?

a) They are initialized to 0
b) They are initialized to -1
c) They contain indeterminate (garbage) values
d) It causes a compile error
Correct Answer: c) They contain indeterminate (garbage) values
Explanation:
Like C-style arrays, an uninitialized std::array of built-in types contains garbage values if declared in a local scope without an initializer.

50. How do you zero-initialize a std::array?

a) std::array<int, 5> arr = {0};
b) std::array<int, 5> arr();
c) std::array<int, 5> arr(0);
d) arr.fill(0);
Correct Answer: a) std::array<int, 5> arr = {0};
Explanation:
Using aggregate initialization like {0} or {} will zero-initialize all elements in the std::array.

51. What is the equivalent function to populate every element of a std::array or std::list with a specific value?

a) assign()
b) fill()
c) set_all()
d) populate()
Correct Answer: b) fill()
Explanation:
The fill() member function assigns the given value to all elements in a std::array. std::list uses assign() for a similar purpose.

52. Which array property makes it unsuitable for situations requiring frequent insertions and deletions at the beginning?

a) Static typing
b) Contiguous memory layout
c) Zero-indexing
d) Pointer decay
Correct Answer: b) Contiguous memory layout
Explanation:
Because array elements are in contiguous memory, inserting at the beginning requires shifting all existing elements, taking O(N) time.

53. In a std::list, what is the time complexity of pushing an element to the front?

a) O(N)
b) O(log N)
c) O(1)
d) O(N^2)
Correct Answer: c) O(1)
Explanation:
Lists manipulate pointers to add elements, making push_front() an O(1) constant time operation.

54. Which operation provides the highest iteration speed from beginning to end?

a) std::list
b) std::forward_list
c) std::array
d) All iterate at exactly the same speed
Correct Answer: c) std::array
Explanation:
Because std::array stores data contiguously, iterating over it is highly cache-friendly and faster than chasing pointers in a list.

55. What does a pointer to an array look like in C++?

a) int* arr[10];
b) int (*arr)[10];
c) int** arr;
d) int arr*[10];
Correct Answer: b) int (*arr)[10];
Explanation:
int (*arr)[10] declares a pointer to an array of 10 integers. Parentheses are needed because [] has higher precedence than *.

56. If int arr[5] = {10, 20, 30, 40, 50}; what is *(arr + 2)?

a) 12
b) 20
c) 30
d) Memory address
Correct Answer: c) 30
Explanation:
arr decays to a pointer to the first element. arr + 2 points to the third element (index 2). Dereferencing it yields 30.

57. Which statement correctly copies the contents of C-style array A to array B of the same size?

a) B = A;
b) B[] = A[];
c) std::copy(A, A + size, B);
d) B.copy(A);
Correct Answer: c) std::copy(A, A + size, B);
Explanation:
C-style arrays do not support direct assignment. You must loop or use a function like std::copy to transfer elements.

58. Which statement correctly copies the contents of std::array A to std::array B of the same type and size?

a) B = A;
b) B.copy(A);
c) std::transfer(A, B);
d) B[] = A[];
Correct Answer: a) B = A;
Explanation:
Unlike C-arrays, std::array objects can be directly assigned to one another using the assignment operator if they have the same size and type.

59. What happens if you use the pop_back() method on an empty std::list?

a) It does nothing
b) It returns false
c) It causes undefined behavior
d) It throws an exception
Correct Answer: c) It causes undefined behavior
Explanation:
Calling pop_back() or pop_front() on an empty list results in undefined behavior. You should always check if it is empty() first.

60. What is the return type of the std::list::size() method?

a) int
b) size_t (or size_type)
c) unsigned int
d) long
Correct Answer: b) size_t (or size_type)
Explanation:
Container size methods in the STL return size_type, which is typically an unsigned integer type like size_t.

61. How do you declare an iterator for a std::list of strings?

a) std::list::iterator it;
b) std::iterator<std::list> it;
c) std::list::iterator it;
d) iterator it;
Correct Answer: a) std::list::iterator it;
Explanation:
The iterator is a nested type within the container template, so the correct syntax is Container::iterator.

62. Which loop is the most modern and safest way to iterate through all elements of a std::list in C++11 and later?

a) for(int i=0; i<list.size(); ++i) { ... }
b) while(!list.empty()) { ... }
c) for(auto& val : list) { ... }
d) for(auto it = list.begin(); it != list.end(); it++)
Correct Answer: c) for(auto& val : list) { ... }
Explanation:
The range-based for loop (introduced in C++11) is the safest and most readable way to traverse containers.

63. What does a reverse iterator (rbegin) point to in an array or list?

a) The first element
b) One position before the first element
c) The last element
d) One position past the last element
Correct Answer: c) The last element
Explanation:
rbegin() returns a reverse iterator pointing to the very last element of the container, while rend() points to one before the first.

64. What is the result of applying the post-increment operator (it++) on a std::list iterator?

a) It increments the value pointed to by the iterator
b) It moves the iterator to the next node in the list
c) It moves the iterator to the next memory address
d) It causes a syntax error
Correct Answer: b) It moves the iterator to the next node in the list
Explanation:
Incrementing a list iterator traverses the linked list by following the 'next' pointer to the subsequent node.

65. Can you use std::binary_search directly on a std::list?

a) No, it causes a compilation error
b) Yes, but it will be highly inefficient (O(N) time)
c) Yes, and it performs in O(log N) time
d) Yes, but only if the list contains integers
Correct Answer: b) Yes, but it will be highly inefficient (O(N) time)
Explanation:
std::binary_search accepts forward iterators, so it compiles. However, because lists lack random access, traversing to the middle elements takes linear time, destroying the performance benefit of binary search.

66. To perform a fast lookup, which data structure is better than a list?

a) std::forward_list
b) std::array or std::vector
c) A doubly linked list
d) A stack
Correct Answer: b) std::array or std::vector
Explanation:
std::array and std::vector provide O(1) random access, whereas lists require O(N) traversal.

67. Which list function can remove elements based on a condition (a predicate)?

a) remove()
b) remove_if()
c) erase_if()
d) delete_if()
Correct Answer: b) remove_if()
Explanation:
remove_if() takes a predicate (a function returning true/false) and removes every element for which the predicate returns true.

68. In the declaration `int arr[2][3] = {{1,2,3}, {4,5,6}};`, what is the value of `arr[1][0]`?

a) 1
b) 3
c) 4
d) 5
Correct Answer: c) 4
Explanation:
arr[1][0] accesses the second row (index 1) and the first column (index 0), which is 4.

69. Which operator is heavily used when working with array decay and pointer arithmetic?

a) The dot (.) operator
b) The arrow (->) operator
c) The dereference (*) operator
d) The scope resolution (::) operator
Correct Answer: c) The dereference (*) operator
Explanation:
Because arrays decay to pointers, the dereference operator (*) is used to access the values at the memory addresses the pointers point to.

70. Why is inserting an element into the middle of a std::list theoretically faster than inserting into the middle of a std::array?

a) std::list stores data in contiguous memory
b) std::list doesn't require memory allocation
c) std::list merely adjusts a few pointers, while std::array requires shifting all subsequent elements
d) It isn't faster; std::array is always faster
Correct Answer: c) std::list merely adjusts a few pointers, while std::array requires shifting all subsequent elements
Explanation:
List insertion is O(1) after the position is found because it only involves rewiring node pointers. (Finding the position takes O(N), though).

71. What is the return type of std::list::emplace_back()?

a) void
b) An iterator to the newly inserted element
c) A reference to the newly inserted element (in C++17)
d) A boolean indicating success
Correct Answer: c) A reference to the newly inserted element (in C++17)
Explanation:
Since C++17, emplace_back() returns a reference to the newly constructed object. Prior to C++17, it returned void.

72. How is emplace_back() different from push_back() in a std::list?

a) emplace_back() is slower
b) emplace_back() constructs the element in-place, avoiding a temporary copy/move
c) emplace_back() can insert multiple elements at once
d) There is no difference
Correct Answer: b) emplace_back() constructs the element in-place, avoiding a temporary copy/move
Explanation:
emplace_back takes constructor arguments and builds the object directly in the node's memory space, which can be more efficient than creating a temporary object and copying/moving it with push_back.

73. What does a std::list node typically contain?

a) Data, a pointer to the next node, and a pointer to the previous node
b) Only data and a pointer to the next node
c) Data and an index integer
d) Only data
Correct Answer: a) Data, a pointer to the next node, and a pointer to the previous node
Explanation:
As a doubly linked list, each node in a std::list holds the element's value along with pointers to both the successor and predecessor nodes.

74. Can you instantiate a std::array with a size of 0?

a) Yes, std::array<int, 0> is valid in C++
b) No, it causes a compile-time error
c) No, the minimum size is 1
d) Yes, but it acts like a dynamic array
Correct Answer: a) Yes, std::array<int, 0> is valid in C++
Explanation:
std::array is explicitly supported by the standard. Calling front() or back() on it yields undefined behavior, but size() returns 0.

75. In memory hierarchy performance, why might std::array perform better than std::list?

a) Because lists allocate more nodes
b) Because contiguous memory takes advantage of CPU cache prefetching
c) Because array elements are smaller
d) Because arrays are processed by the GPU
Correct Answer: b) Because contiguous memory takes advantage of CPU cache prefetching
Explanation:
Arrays are cache-friendly. Modern CPUs fetch chunks of memory into cache; with contiguous memory, the next elements are already in the fast cache.

76. Which feature of C-style arrays causes the biggest security vulnerabilities?

a) Inability to hold floating point numbers
b) Lack of bounds checking leading to buffer overflows
c) Zero-based indexing
d) Row-major storage
Correct Answer: b) Lack of bounds checking leading to buffer overflows
Explanation:
Because C-arrays do not check if an index is out of bounds, hackers can overwrite adjacent memory (buffer overflow), leading to severe security exploits.

77. What is the memory overhead of a std::list of integers compared to a std::array of integers?

a) There is no overhead
b) std::list has significant overhead due to storing two pointers per element
c) std::array has more overhead because it pre-allocates memory
d) std::list has a single pointer overhead per element
Correct Answer: b) std::list has significant overhead due to storing two pointers per element
Explanation:
Every element in a std::list requires allocation for the data itself plus a forward and backward pointer, adding at least 8 to 16 bytes of overhead per integer.

78. What is the type of the elements in argv (char* argv[]) passed to the main function?

a) Characters
b) Strings
c) Pointers to characters (C-style strings)
d) Integers
Correct Answer: c) Pointers to characters (C-style strings)
Explanation:
argv is an array of pointers to characters. Each pointer points to a null-terminated C-style string representing a command-line argument.

79. Can an array be the return type of a C++ function?

a) Yes, a function can return a built-in array directly by value
b) No, functions cannot return built-in arrays directly; they must return a pointer or a wrapper like std::array
c) Only if the array is multidimensional
d) Only if the array is static
Correct Answer: b) No, functions cannot return built-in arrays directly; they must return a pointer or a wrapper like std::array
Explanation:
C++ functions cannot return built-in array types. They must return a pointer, a struct containing an array, a std::array, or a std::vector.

80. Which of the following creates a reference to an array of 5 integers?

a) int& arr[5];
b) int (&arr)[5];
c) int arr&[5];
d) ref arr[5];
Correct Answer: b) int (&arr)[5];
Explanation:
Parentheses are necessary: int (&arr)[5]. Without them, int& arr[5] implies an array of references, which is illegal in C++.

81. What is illegal in C++ regarding arrays of references?

a) They require pointers
b) They are perfectly legal
c) C++ does not allow arrays of references
d) They can only be declared dynamically
Correct Answer: c) C++ does not allow arrays of references
Explanation:
References are not objects in C++ (they have no storage identity), so you cannot create arrays of them. You can, however, use std::reference_wrapper.

82. How do you define an iterator for std::forward_list?

a) std::forward_list::iterator
b) std::forward_iterator
c) std::list::iterator
d) forward_list.iterator
Correct Answer: a) std::forward_list::iterator
Explanation:
Like other containers, the iterator is accessed via the scope of the container template: std::forward_list::iterator.

83. Does std::forward_list support the insert() method?

a) Yes, it functions identically to std::list
b) Yes, but it only inserts at the end
c) No, it supports insert_after() instead
d) No, it only supports push_front()
Correct Answer: c) No, it supports insert_after() instead
Explanation:
Because it only has forward pointers, it can only efficiently insert a node *after* a known node, using insert_after().

84. To insert an element at the very beginning of a std::forward_list using insert_after, what iterator do you pass?

a) begin()
b) before_begin()
c) start()
d) front()
Correct Answer: b) before_begin()
Explanation:
std::forward_list provides a before_begin() iterator, which acts as a dummy node before the first element, allowing insertion at the absolute front via insert_after().

85. Which of these correctly swaps the contents of two lists `list1` and `list2` in O(1) time?

a) list1 = list2;
b) std::swap(list1, list2);
c) list1.swap_with(list2);
d) Both a and c
Correct Answer: b) std::swap(list1, list2);
Explanation:
std::swap (or list1.swap(list2)) swaps internal pointers to the head and tail, taking O(1) time. Assignment (list1 = list2) takes O(N) time because it copies elements.

86. If you dynamically allocate memory using `int* p = new int[5];`, how is the memory zero-initialized?

a) int* p = new int[5](https://www.google.com/search?q=0);
b) int* p = new int[5]{0};
c) int* p = new int[5] = 0;
d) You cannot initialize dynamic arrays
Correct Answer: b) int* p = new int[5]{0};
Explanation:
In modern C++ (C++11 and later), you can use aggregate initialization with new[]: new int[5]{0} initializes all 5 elements to 0.

87. Which std::list method allows removing elements if a specified boolean condition is met?

a) delete_if()
b) filter()
c) remove_if()
d) exclude()
Correct Answer: c) remove_if()
Explanation:
std::list::remove_if() evaluates a unary predicate for each element and removes those for which the predicate evaluates to true.

88. What is the maximum theoretical size of a std::list?

a) list.max_size()
b) The size of RAM
c) 65535
d) Determined by std::vector
Correct Answer: a) list.max_size()
Explanation:
All standard containers provide a max_size() method that returns the maximum number of elements the container can theoretically hold based on system architecture and allocator constraints.

89. Why might you choose a std::list over a std::vector?

a) When you need random access
b) When you have frequent insertions/deletions in the middle of the container
c) When memory is tight
d) When cache-locality is critical
Correct Answer: b) When you have frequent insertions/deletions in the middle of the container
Explanation:
Lists allow O(1) insertions and deletions anywhere (once the position iterator is known), whereas vectors require shifting elements.

90. What header contains algorithms like std::find that work on both arrays and lists?

a)
b)
c)
d)
Correct Answer: c)
Explanation:
The header provides a vast majority of STL functions (like find, count, copy) that operate on iterator ranges.

91. If `int arr[] = {1, 2, 3};`, what is the value of `2[arr]` in C++?

a) Syntax Error
b) 3
c) Undefined Behavior
d) 1
Correct Answer: b) 3
Explanation:
Due to pointer arithmetic properties inherited from C, arr[2] is equivalent to *(arr + 2), which is also equivalent to *(2 + arr), so 2[arr] is valid syntax and equals 3.

92. Which of the following is true regarding passing arrays to functions?

a) Arrays are passed by value by default
b) An array size parameter is unnecessary because the array knows its size
c) Arrays decay to pointers, so modifications in the function affect the original array
d) Only the first dimension is passed
Correct Answer: c) Arrays decay to pointers, so modifications in the function affect the original array
Explanation:
Because a pointer to the original memory is passed, changes made using the array index inside the function modify the original elements.

93. How do you find the first element in a std::list that is greater than 10?

a) Using std::find_if()
b) Using list.search(10)
c) Using std::search_greater(10)
d) Using list.find()
Correct Answer: a) Using std::find_if()
Explanation:
std::find_if accepts the begin and end iterators along with a lambda or predicate (e.g., [](int x){ return x > 10; }) to find the element.

94. Can an array contain references?

a) Yes
b) No
c) Only if dynamically allocated
d) Only constant references
Correct Answer: b) No
Explanation:
Arrays of references are illegal in C++. Standard array elements must be assignable and have a size; references do not.

95. What does a std::list's sort() method use internally in most implementations?

a) Quicksort
b) Mergesort
c) Bubblesort
d) Heapsort
Correct Answer: b) Mergesort
Explanation:
Mergesort is ideal for linked lists because it can merge sublists simply by reassigning pointers without needing random access.

96. If you want a fixed-size array that performs bounds checking via the at() method, you should use:

a) int arr[10];
b) std::array<int, 10>
c) std::vector
d) std::list
Correct Answer: b) std::array<int, 10>
Explanation:
std::array provides a compile-time fixed size along with the safety of member functions like at() which perform bounds checking.

97. Which of these containers requires memory reallocation when growing past its capacity?

a) std::list
b) std::forward_list
c) std::vector
d) std::array
Correct Answer: c) std::vector
Explanation:
std::vector allocates contiguous memory and must reallocate and copy/move when it outgrows capacity. Lists allocate single nodes as needed, and arrays cannot grow.

98. When iterating with `auto it = mylist.begin();`, what is the type of `it`?

a) A pointer to the node
b) An integer index
c) A std::list::iterator
d) A reference to the data
Correct Answer: c) A std::list::iterator
Explanation:
The 'auto' keyword deduces the type returned by mylist.begin(), which is std::list::iterator.

99. What is the difference between `list.erase(it)` and `list.remove(val)`?

a) erase removes by iterator position, remove removes by value match
b) erase removes by value, remove removes by iterator
c) They are exactly the same
d) erase works on all elements, remove works on one element
Correct Answer: a) erase removes by iterator position, remove removes by value match
Explanation:
erase() deletes elements at specific iterator locations, whereas remove() searches the list for a specific value and deletes all matching elements.

100. What is std::distance(a, b) used for?

a) Calculating the spatial distance between two memory addresses
b) Finding the number of steps (elements) between two iterators
c) Checking if two arrays overlap
d) Allocating memory between a and b
Correct Answer: b) Finding the number of steps (elements) between two iterators
Explanation:
std::distance calculates the number of increments needed to go from iterator 'a' to iterator 'b'.

101. How does std::distance(a, b) perform on a std::list?

a) O(1) time
b) O(N) time
c) O(log N) time
d) It causes a compiler error
Correct Answer: b) O(N) time
Explanation:
Because std::list iterators are bidirectional (not random access), std::distance must step through the list one by one, taking linear O(N) time.

102. Is it possible to have an array of lists?

a) No, arrays cannot hold STL containers
b) Yes, e.g., std::list arr[10];
c) Yes, but they must be pointers to lists
d) No, it causes undefined behavior
Correct Answer: b) Yes, e.g., std::list arr[10];
Explanation:
You can declare an array of lists perfectly fine. It is often used to implement a hash table using chaining.

103. Which of these expressions is used to access the last element of a std::array `arr`?

a) arr.end()
b) arr.back()
c) arr.last()
d) arr[arr.size()]
Correct Answer: b) arr.back()
Explanation:
The back() member function returns a reference to the last element. arr.end() returns an iterator past the end.

104. For a statically allocated array `int arr[5] = {1, 2};`, what is the value of `arr[4]`?

a) Garbage value
b) 0
c) 2
d) Undefined
Correct Answer: b) 0
Explanation:
When an array is partially initialized, the remaining uninitialized elements are automatically initialized to zero.

105. What is the key danger of returning a local array from a function using a pointer?

a) The pointer cannot be dereferenced
b) The local array's memory is deallocated when the function returns, causing a dangling pointer
c) The array size is unknown
d) It causes a memory leak
Correct Answer: b) The local array's memory is deallocated when the function returns, causing a dangling pointer
Explanation:
Local arrays are stored on the stack and destroyed when the function ends. Returning a pointer to them yields undefined behavior upon access.

106. Which C++ cast is safest for converting an array of bytes to a struct pointer? (Advanced usage)

a) static_cast
b) dynamic_cast
c) reinterpret_cast
d) const_cast
Correct Answer: c) reinterpret_cast
Explanation:
reinterpret_cast is used for low-level reinterpretation of bit patterns, such as mapping a byte array over a struct.

107. Why does std::array require two template parameters? (e.g., std::array<int, 5>)

a) One for type, one for the allocator
b) One for type, one for the size
c) One for size, one for the default value
d) Because it derives from pair
Correct Answer: b) One for type, one for the size
Explanation:
std::array is fixed-size at compile time. Its type signature includes both the element data type and the exact number of elements.

108. If you need a container that grows in size but you NEVER insert in the middle, only append at the end, what is best?

a) std::list
b) std::forward_list
c) std::vector
d) std::array
Correct Answer: c) std::vector
Explanation:
std::vector is optimized for O(1) amortized insertion at the end and offers fast contiguous iteration.

109. How do you access the value an iterator points to in a list?

a) it.value()
b) it.get()
c) *it
d) it->
Correct Answer: c) *it
Explanation:
Iterators act like pointers. You dereference them using the asterisk (*) operator to access the underlying element.

110. If a std::list iterator `it` points to an object, how do you call a member function `func()` of that object?

a) it.func()
b) it->func()
c) it::func()
d) *it.func()
Correct Answer: b) it->func()
Explanation:
The arrow operator (->) is overloaded on iterators to access members of the object being pointed to. (*it).func() is also correct but not an option.

111. What is the standard C++11 method to convert a C-array to a std::array?

a) std::to_array (C++20)
b) std::make_array
c) std::array::copy
d) It happens implicitly
Correct Answer: a) std::to_array (C++20)
Explanation:
Introduced in C++20, std::to_array converts a built-in array to a std::array. (Note: standard C++11 lacks a direct one-liner standard library function for this without manual copying or std::copy).

112. Is it valid to subtract two std::list iterators (e.g., it2 - it1)?

a) Yes, it returns the distance
b) No, because list iterators do not support subtraction
c) Yes, it returns a pointer
d) No, because list iterators are const
Correct Answer: b) No, because list iterators do not support subtraction
Explanation:
List iterators are bidirectional, not random-access. The subtraction operator requires random-access iterators. You must use std::distance() instead.

113. What happens when you call `cbegin()` on a container?

a) It clears the container and begins anew
b) It returns a const_iterator pointing to the first element
c) It counts the elements from the beginning
d) It returns a C-style pointer to the beginning
Correct Answer: b) It returns a const_iterator pointing to the first element
Explanation:
cbegin() strictly returns a constant iterator, ensuring the elements of the container cannot be modified through that iterator.

114. Can you use std::list to implement a Queue?

a) No, a list cannot function as a queue
b) Yes, by pushing at the back and popping from the front
c) Yes, but it requires allocating contiguous blocks
d) No, it is strictly a stack
Correct Answer: b) Yes, by pushing at the back and popping from the front
Explanation:
A queue is FIFO (First-In-First-Out). std::list can push_back and pop_front in O(1) time, making it an acceptable underlying container for a queue.

115. What is the memory complexity of std::list compared to the amount of data 'N'?

a) O(1)
b) O(N)
c) O(N^2)
d) O(log N)
Correct Answer: b) O(N)
Explanation:
The memory grows linearly with the number of elements N. Each element takes constant O(1) space, so N elements take O(N) space.

116. In a 3D array `int arr[2][3][4];`, what is the total number of integer elements?

a) 9
b) 24
c) 12
d) 8
Correct Answer: b) 24
Explanation:
The total capacity is the product of all dimensions: 2 * 3 * 4 = 24 elements.

117. When defining an array of strings, which is safest and easiest to manage in C++?

a) char** arr
b) char arr[10][256]
c) std::array<std::string, 10>
d) std::string* arr = new std::string[10]
Correct Answer: c) std::array<std::string, 10>
Explanation:
std::array combined with std::string provides automatic memory management, deep copying, bounds safety, and rich member functions.

118. If you dynamically allocate an array of objects: `MyClass* arr = new MyClass[10];`, what happens?

a) Memory is allocated, but no constructors are called
b) The default constructor is called 10 times
c) A compilation error occurs if MyClass has no parameterized constructor
d) Only the first object is constructed
Correct Answer: b) The default constructor is called 10 times
Explanation:
When allocating an array of objects with new[], C++ automatically invokes the default constructor for every element in the array.

119. If MyClass has NO default constructor, can you easily allocate `new MyClass[10]`?

a) Yes, C++ will generate one automatically
b) Yes, memory is just left uninitialized
c) No, it will cause a compile-time error
d) Yes, but you must manually call the constructor later
Correct Answer: c) No, it will cause a compile-time error
Explanation:
Arrays require default constructors to initialize the elements. If a default constructor doesn't exist (because only parameterized ones were defined), `new MyClass[10]` will fail to compile.

120. Which header provides std::distance and std::advance?

a)
b)
c)
d)
Correct Answer: a)
Explanation:
Utility functions for iterators like advance, distance, next, and prev are found in the header.

121. What does `std::advance(it, 3)` do on a list iterator?

a) Adds 3 to the value pointed to by the iterator
b) Moves the iterator forward by 3 positions
c) Creates 3 new elements
d) Returns a new iterator 3 positions ahead without modifying 'it'
Correct Answer: b) Moves the iterator forward by 3 positions
Explanation:
std::advance modifies the iterator directly, moving it forward by the specified number of steps (or backward if negative).

122. Which of these correctly returns an iterator to the 4th element of a std::list?

a) list.begin() + 3
b) list[3]
c) auto it = list.begin(); std::advance(it, 3);
d) list.at(3)
Correct Answer: c) auto it = list.begin(); std::advance(it, 3);
Explanation:
Because list iterators cannot be added directly (like begin() + 3), you must use std::advance or std::next to step forward.
← Previous: 400+ C++ Interview Questions MCQ
Next →: C++ Classes and Objects - MCQs
NewC++ Pointers and References - MCQs

C++ Pointers and References - MCQs

In C++, pointers and references are powerful features that provide direct access to memory and allow for highly efficient data…

By MCQs Generator
NewC++ Variables & Data Types MCQs

C++ Variables & Data Types MCQs

Variables and data types form the core building blocks of any C++ application, defining how data is stored, represented, and…

By MCQs Generator
New
No Image

400+ C++ Interview Questions MCQ

1. What is an array in C++? a) A dynamic data structure that can change size automatically b) A collection…

By MCQs Generator