C++ Exercises with Answers
Practise C++ with 144 interactive exercises: multiple choice, fill-in-the-blank, output prediction and debugging. Every exercise gives instant feedback, a hint and the full solution.
Topic All topics Introduction Variables & Input Operators & Math Strings if / else Loops Functions Arrays & Vectors Recursion Formatting & Streams Structs & Enums Pointers Classes & Objects Maps & Sets (STL) Algorithms & Lambdas Exceptions Files (fstream) Inheritance & Polymorphism Operator Overloading Headers, Files & CMake Smart Pointers Move Semantics Templates optional & variant Threads & Concurrency Scope and Linkage Const Correctness Casts and Numeric Safety Array and Span String View Lifetimes Iterator Invalidation List and Deque Container Adaptors Unordered Containers Chrono and Dates Random Generation Friend Access Multiple Inheritance Special Members and Guarantees Advanced Templates Concepts and Requires Ranges and Views Debugging and Testing CMake and Builds
All types Fill in the blanks Predict the output Multiple choice
Any level Easy Medium Hard
Score 0 / 144
cout << "Score: " << 4 * 5 << endl ;
A Score: 4 * 5 B Score:20 C 20 D Score: 20
4 * 5 is calculated first, then printed after the text.
Show answer
Which line must a program include to use cout?
A #include <stdio> B #include <iostream> C #include <cout> D import iostream;
cout and cin come from the iostream library.
Show answer
cout << 9 / 4 << " " << 9 % 4 << endl ;
A 2.25 1 B 2 2 C 2 1 D 2.25 0.25
Whole-number division gives 2, and the remainder is 1.
Show answer
What does return 0; at the end of main mean?
A The program finished successfully B Print 0 C Restart the program D An error happened
A non-zero value usually signals an error.
Show answer
int a = 10 ;
a = a + 5 ;
a = a * 2 ;
cout << a;
A 15 B 30 C 20 D 25
a becomes 15, then 30.
Show answer
int x = 7 ;
int y = 2 ;
cout << x / y << " " << ( double ) x / y;
A 3.5 3.5 B 3 3 C 4 3.5 D 3 3.5
int / int gives 3; casting x to double gives 3.5.
Show answer
Which line reads a full sentence, including spaces, into s?
A getline(cin, s); B cin >> s; C cin.read(s); D s = cin;
getline reads until the end of the line.
Show answer
auto x = 5 / 2 ;
auto y = 5 / 2.0 ;
cout << x << " " << y << endl ;
A 2.5 2.5 B 2 2 C 3 2.5 D 2 2.5
auto takes the type of the result: int for 5 / 2 and double for 5 / 2.0.
Show answer
Complete the code so it prints the remainder of 20 divided by 6.
cout << 20 6 << endl ;
% gives the remainder: 20 % 6 is 2.
Check answer Show solution
cout << 11 / 4 << endl ;
A 2.75 B 3 C 2.0 D 2
Both are ints, so the decimals are dropped.
Show answer
int x = 10 ;
x -= 4 ;
x *= 3 ;
cout << x << endl ;
A 6 B 26 C 18 D 30
10 minus 4 is 6, and 6 times 3 is 18.
Show answer
Which expression gives 2.5?
A 5 / 2 B static_cast<double>(5 / 2) C static_cast<double>(5) / 2 D static_cast<int>(5.0) / 2
Convert before dividing; converting after gives 2.
Show answer
Why is int big = 2147483647; big++; a problem in C++?
A It's a compile error B Signed integer overflow is undefined behaviour C big becomes a long D big stays the same
The result can't be relied on; use a larger type.
Show answer
Complete the code so it prints the number of characters in city.
string city = "Lisbon" ;
cout << city. ( ) ;
size() (or length()) returns the number of characters.
Check answer Show solution
string s = "Computer" ;
cout << s. substr ( 3 , 3 ) ;
A Com B put C pute D mpu
Start at index 3 ("p") and take 3 characters.
Show answer
string s = "banana" ;
s. replace ( 0 , 1 , "B" ) ;
s. erase ( 3 ) ;
cout << s;
A Banana B Ban C Bana D ban
The first letter becomes B, then everything from index 3 onwards is erased.
Show answer
What does find return when the text isn't found?
A -1 B 0 C An exception D string::npos
Compare the result with string::npos.
Show answer
cout << stoi ( "42abc" ) + 1 ;
A 43 B An error C 42abc1 D 1
stoi reads the leading digits and stops at the first letter.
Show answer
int x = 4 ;
if ( x > 5 ) cout << "A" ;
else if ( x > 3 ) cout << "B" ;
else cout << "C" ;
A B B A C C D BC
4 isn't above 5, but it is above 3.
Show answer
int n = 2 ;
switch ( n) {
case 1 : cout << "one " ;
case 2 : cout << "two " ;
case 3 : cout << "three " ;
}
A two B one two three C Nothing D two three
There's no break, so execution falls through from case 2 into case 3.
Show answer
Which condition is true when x is between 1 and 10, exclusive?
A 1 < x < 10 B x > 1 || x < 10 C x > 1 && x < 10 D x == 1 to 10
Each comparison must be written separately and joined with &&.
Show answer
int n = 7 ;
cout << ( n % 2 == 0 ? "even" : "odd" ) << endl ;
A even B odd C 1 D 7
7 % 2 is 1, so the condition is false.
Show answer
Predict the outputeasy Loops
for ( int i = 10 ; i > 0 ; i -= 3 ) {
cout << i << " " ;
}
A 10 7 4 1 -2 B 10 7 4 1 C 10 7 4 D 9 6 3
After 1 comes -2, which fails the condition i > 0.
Show answer
Predict the outputmedium Loops How many stars does this print?
for ( int a = 0 ; a < 3 ; a++ )
for ( int b = 0 ; b < 4 ; b++ )
cout << "*" ;
A 7 B 3 C 12 D 4
The inner loop runs 4 times for each of the 3 outer passes: 3 x 4 = 12.
Show answer
Multiple choicemedium Loops Which loop is best for a menu that must appear at least once?
A for B while C switch D do-while
do-while runs its body before checking the condition.
Show answer
Predict the outputmedium Loops
for ( int i = 0 ; i < 10 ; i++ ) {
if ( i == 4 ) break ;
if ( i % 2 == 1 ) continue ;
cout << i << " " ;
}
A 0 2 B 0 1 2 3 C 0 2 4 D 1 3
Odd numbers are skipped and the loop stops at 4.
Show answer
int add ( int a, int b = 5 ) { return a + b; }
cout << add ( 1 ) << " " << add ( 1 , 1 ) ;
A 6 6 B 1 2 C 5 2 D 6 2
add(1) uses the default b = 5.
Show answer
void bump ( int & n) { n++ ; }
int x = 3 ;
bump ( x) ;
bump ( x) ;
cout << x;
A 3 B 5 C 4 D 6
n is a reference to x, so x is increased twice.
Show answer
What does const string& name mean for a parameter?
A A copy of the string that can be changed B A string that must be empty C The caller's string, without copying it, and it can't be changed D A constant global variable
The reference avoids a copy and const prevents changes.
Show answer
Which declaration lets a function change the caller's variable?
A void addOne(int n) B void addOne(int& n) C void addOne(const int n) D int addOne()
The & makes n a reference to the caller's variable.
Show answer
Complete the code to add 42 to the end of the vector.
vector < int > v;
v. ( 42 ) ;
push_back adds an item to the end of a vector.
Check answer Show solution
vector < char > letters = { 'c' , 'o' , 'd' , 'e' } ;
cout << letters[ 1 ] << letters. size ( ) ;
A c4 B o3 C o4 D d4
Index 1 is the second item, and there are 4 items.
Show answer
vector < int > v = { 1 , 2 , 3 } ;
for ( int & x : v) x = x * 10 ;
v. pop_back ( ) ;
for ( int x : v) cout << x << " " ;
A 1 2 B 10 20 30 C 20 30 D 10 20
Each item is multiplied by 10, then the last one is removed.
Show answer
What does v.at(10) do if v has only 3 items?
A Returns 0 B Returns a random value C Adds items up to index 10 D Reports an out-of-range error
at() checks the index; [] does not.
Show answer
vector < int > v = { 3 , 1 , 4 } ;
v. push_back ( 1 ) ;
cout << v. size ( ) << " " << v. back ( ) << endl ;
A 4 1 B 3 4 C 4 4 D 3 1
push_back adds a fourth item, which is now the last one.
Show answer
Complete the base case so the function stops at zero.
int sumTo ( int n) {
if ( n == ) return 0 ;
return n + sumTo ( n - 1 ) ;
}
When n reaches 0 there's nothing left to add.
Check answer Show solution
Using the lesson's factorial function, what does factorial(4) return?
A 4 B 10 C 16 D 24
4 times 3 times 2 times 1.
Show answer
int f ( int n) {
if ( n == 0 ) return 0 ;
return 2 + f ( n - 1 ) ;
}
cout << f ( 5 ) << endl ;
A 5 B 7 C 10 D 32
Five calls each add 2 before the base case returns 0.
Show answer
What happens when recursion never reaches a base case?
A It runs for ever without problems B The call stack fills up and the program crashes with a stack overflow C The compiler refuses to build it D It returns 0
Each call adds a frame until the stack runs out.
Show answer
Why is naive recursive Fibonacci slow?
A Recursion is always slow B It uses doubles C It has no base case D It recalculates the same values over and over
Memoization stores each answer so it's calculated once.
Show answer
struct Box { int w; int h; } ;
Box b{ 3 , 4 } ;
b. w = 5 ;
cout << b. w * b. h ;
A 12 B 15 C 9 D 20
w becomes 5, so 5 x 4 = 20.
Show answer
How should a function that only reads a large struct take it?
A By const reference: f(const Product& p) B By value: f(Product p) C By reference: f(Product& p) D It can't take a struct
const& avoids copying and prevents changes.
Show answer
enum class Level { Low , Mid , High } ;
cout << static_cast< int > ( Level : : High ) ;
A 3 B 2 C High D 1
Values start at 0, so High is 2.
Show answer
What's the only difference between struct and class in C++?
A Structs can't have functions B Struct members are public by default; class members are private by default C Classes can't be in vectors D Structs live on the stack only
Otherwise they're identical.
Show answer
Complete the code so p stores the address of age.
int age = 20 ;
int * p = age;
& in front of a variable gives its address.
Check answer Show solution
int a = 8 ;
int * p = & a;
* p = * p * 2 ;
cout << a;
A 16 B 8 C An address D 2
Changing *p changes a.
Show answer
int arr[ 4 ] = { 5 , 10 , 15 , 20 } ;
int * p = arr;
cout << * ( p + 3 ) << " " << * p;
A 15 5 B 20 10 C 20 5 D An address
p + 3 points at arr[3], and p still points at arr[0].
Show answer
Which line correctly reads the name through a pointer to a struct?
A p->name B p.name C *p.name D &p.name
-> is short for (*p).name. p.name would apply to p.name.
Show answer
When is a pointer a better choice than a reference?
A Always B When the value might be "nothing" (nullptr) or needs to point somewhere else later C When passing large objects D When the value never changes
References can't be null or be reseated.
Show answer
class Counter {
int n = 0 ;
public :
void add ( ) { n += 2 ; }
int get ( ) const { return n; }
} ;
Counter a, b;
a. add ( ) ; a. add ( ) ; b. add ( ) ;
cout << a. get ( ) << " " << b. get ( ) ;
A 6 6 B 2 4 C 3 3 D 4 2
Each object has its own n.
Show answer
What is a member initializer list?
A A list of all objects B A vector inside a class C A list of public functions D The part after a constructor's colon that initialises members directly
Account(string o) : owner(o) {}
Show answer
What does const after a member function's brackets mean?
A The function returns a constant B The function can't be called C The function doesn't change the object's members D The function is static
It can then be called on const objects.
Show answer
In what order are messages printed when an object made in a block reaches the block's closing brace?
A The constructor runs again B Its destructor runs at that moment C Nothing happens until the program ends D Its destructor runs before its constructor
Objects are destroyed when they go out of scope.
Show answer
Complete the code so it stores a score for "Ana".
map< string , int > scores;
scores. ( { "Ana" , 82 } ) ;
insert adds a key-value pair. scores["Ana"] = 82 would work too.
Check answer Show solution
set< int > s = { 5 , 1 , 5 , 3 } ;
cout << s. size ( ) ;
A 3 B 4 C 2 D 5
A set keeps only 1, 3 and 5.
Show answer
map< string , int > m;
cout << m[ "x" ] << " " << m. size ( ) ;
A An error B 0 1 C 0 0 D x 1
Reading m["x"] inserts the key with the value 0.
Show answer
Which container gives fast lookups by key with no particular order?
A std::map B std::vector C std::set D std::unordered_map
It's hash-based, so it doesn't keep keys sorted.
Show answer
What does m.find(k) != m.end() check?
A Whether the map is empty B Whether k is the last key C Whether the key k exists in the map D Whether the value equals k
find returns end() when the key isn't found.
Show answer
Complete the call that sorts the whole vector.
sort ( v. ( ) , v. end ( ) ) ;
begin() and end() describe the whole range.
Check answer Show solution
vector < int > v = { 3 , 8 , 1 , 8 } ;
cout << count ( v. begin ( ) , v. end ( ) , 8 ) << endl ;
A 2 B 1 C 8 D 4
count returns how many items equal 8.
Show answer
vector < int > v = { 4 , 9 , 2 } ;
cout << accumulate ( v. begin ( ) , v. end ( ) , 10 ) << endl ;
A 15 B 10 C 72 D 25
The starting value 10 plus 4, 9 and 2.
Show answer
What does [&total] mean in a lambda?
A total is copied into the lambda B total is a parameter C The lambda uses the real total by reference and can change it D The lambda returns total
& captures by reference.
Show answer
Why does remove_if need to be followed by erase?
A remove_if deletes the wrong items B remove_if only moves the kept items forward; erase actually shrinks the container C erase sorts the vector D It doesn't; remove_if is enough
Together they form the erase-remove idiom.
Show answer
Complete the code so it throws an error for a negative age.
if ( age < 0 ) invalid_argument ( "Age can't be negative" ) ;
throw raises the exception and leaves the function.
Check answer Show solution
How should exceptions usually be caught?
A By value B By pointer C By const reference D As an int
catch (const exception& e) avoids copying and slicing.
Show answer
try {
cout << "A" ;
throw runtime_error ( "x" ) ;
cout << "B" ;
} catch ( const exception& e) {
cout << "C" ;
}
cout << "D" << endl ;
A ABCD B AD C ABD D ACD
B is skipped by the throw; C runs in the catch; D runs afterwards.
Show answer
Which call throws out_of_range for an invalid index?
A v[10] B v.front() C v.size() D v.at(10)
at() checks the index; [] doesn't.
Show answer
What happens to local objects when an exception leaves a function?
A Their destructors run as the stack unwinds B They're leaked C They're copied to the catch block D The program crashes
That's why RAII types clean up automatically.
Show answer
Which mode adds to the end of an existing file?
A ios::in B ios::out C ios::app D ios::end
app means append.
Show answer
A file contains 3 4 5. What does this print?
ifstream in ( "nums.txt" ) ;
int x, sum = 0 ;
while ( in >> x) sum += x;
cout << sum;
A 12 B 345 C 5 D 0
The loop reads each number until the file ends.
Show answer
Why is while (!in.eof()) a bad loop condition?
A eof() doesn't exist B eof is only set after a read fails, so the last item is often processed twice C It reads the file backwards D It only works for binary files
Loop on the read itself instead.
Show answer
stringstream ss ( "red,green,blue" ) ;
string part;
getline ( ss, part, ',' ) ;
getline ( ss, part, ',' ) ;
cout << part;
A red B blue C green D red,green
The second getline reads the second field.
Show answer
Complete the line so Car inherits publicly from Vehicle.
class Car : Vehicle {
} ;
Public inheritance keeps the base class's public members public.
Check answer Show solution
Complete the base class so derived classes can override sound().
class Animal {
public :
string sound ( ) const { return "..." ; }
} ;
virtual enables polymorphic overriding.
Check answer Show solution
struct A { virtual string hi ( ) const { return "A" ; } virtual ~ A ( ) = default ; } ;
struct B : A { string hi ( ) const override { return "B" ; } } ;
B b;
const A& ref = b;
cout << ref. hi ( ) ;
A A B AB C B D A compile error
hi() is virtual and ref refers to a B.
Show answer
What makes a class abstract?
A Having private members B Having at least one pure virtual function (= 0) C Having a destructor D Inheriting from another class
You can't create objects of an abstract class directly.
Show answer
A Copying a derived object into a base-class value, losing the derived part B Splitting a class into two files C Deleting part of an object D Removing virtual functions
Use references or pointers to keep the full object.
Show answer
Complete the function name that overloads the + operator.
Vec2 ( const Vec2 & o) const {
return { x + o. x , y + o. y } ;
}
An overloaded operator's name is operator followed by the symbol.
Check answer Show solution
Why must operator<< for printing be a non-member function?
A Non-member functions are faster B The left operand is the stream, not your object C Members can't return values D It must be static
In cout << v, cout comes first.
Show answer
Using the lesson's Vec2, what does cout << Vec2{1, 2} + Vec2{3, 4}; print?
A (1, 2)(3, 4) B (3, 8) C (4, 6) D 10
Components are added: 1 + 3 and 2 + 4.
Show answer
What should operator+= return?
A A reference to *this B void C A new object D bool
Returning *this allows chaining like (a += b) += c.
Show answer
Which operator do std::sort and std::set use by default?
A operator== B operator> C operator<= D operator<
Defining < gives your type a natural order.
Show answer
Complete the first line of a header so it can't be included twice.
#pragma
double circleArea ( double radius) ;
#pragma once tells the compiler to include the file only once per source file.
Check answer Show solution
Where do function bodies usually go?
A In .cpp source files B In header files C In CMakeLists.txt D In main only
Headers declare; source files define.
Show answer
What does "undefined reference to geo::circleArea(double)" usually mean?
A The header has a typo in #include B The definition wasn't found: the .cpp file wasn't compiled or the signatures don't match C The function is defined twice D The namespace is missing from main
It's a linker error, not a compiler error.
Show answer
Which include style is for your own project headers?
A #include <geometry.h> B import geometry C #using geometry.h D #include "geometry.h"
Quotes search the project first; angle brackets are for libraries.
Show answer
Why should a header never contain using namespace std;?
A It forces the directive on every file that includes the header, risking name clashes B It slows compiling C Headers can't use namespaces D It's a syntax error
Write std:: in full inside headers.
Show answer
Complete the line that creates a heap object owned by a unique_ptr.
auto p = < int > ( 42 ) ;
make_unique creates the object and its owning unique_ptr.
Check answer Show solution
What does a unique_ptr do when it's destroyed?
A Nothing B Deletes the object it owns C Copies the object D Moves the object to the stack
That's how it prevents leaks.
Show answer
auto a = make_shared< int > ( 1 ) ;
auto b = a;
auto c = b;
cout << a. use_count ( ) ;
A 3 B 1 C 2 D 0
a, b and c all share ownership.
Show answer
How do you transfer ownership from one unique_ptr to another?
A b = a; B b = a.copy(); C b = &a; D b = std::move(a);
unique_ptr can be moved but not copied.
Show answer
What problem does weak_ptr solve?
A Slow allocation B Reference cycles where shared_ptrs keep each other alive forever C Copying unique_ptrs D Stack overflow
weak_ptr observes without increasing the count.
Show answer
Complete the line so b takes over a's contents instead of copying them.
vector < int > b = std : : ( a) ;
std::move allows the move constructor to be used.
Check answer Show solution
What happens to a vector after it's been moved from with the move constructor?
A It's left empty B It still has all its items C It's deleted D It holds a copy
Its memory now belongs to the new vector.
Show answer
What does T&& mean as a parameter type?
A An rvalue reference, which binds to temporaries that may be moved from B A pointer to a pointer C A reference to a const D A copy
Move constructors take T&&.
Show answer
Which adds an object by building it directly inside the vector?
A push_back(T(...)) B insert(...) C emplace_back(...) D std::move(...)
emplace_back passes its arguments to the constructor in place.
Show answer
Why mark a move constructor noexcept?
A It's required to compile B Containers like vector only move elements during growth if the move can't throw C It makes the class const D It disables copying
Otherwise vector copies to keep its strong safety guarantee.
Show answer
template < typename T>
T twice ( T x) { return x + x; }
cout << twice ( 4 ) << " " << twice ( string ( "ab" ) ) ;
A 8 abab B 8 ab C 44 abab D An error
+ adds ints and joins strings.
Show answer
What happens when you call a function template with a new type?
A It runs more slowly B The compiler generates a version of the function for that type C The type is converted to int D It's interpreted at run time
This is called instantiation.
Show answer
template < typename T>
class Box {
T v;
public :
Box ( T x) : v ( x) { }
T get ( ) const { return v; }
} ;
Box < double > b ( 7 ) ;
cout << b. get ( ) / 2 ;
A 3 B 7 C An error D 3.5
T is double, so 7 is stored as 7.0 and divides to 3.5.
Show answer
Why are templates usually defined in header files?
A Headers compile faster B Templates can't be in .cpp files C The compiler needs the full definition wherever the template is instantiated D It's only a style rule
Otherwise the linker can't find the instantiated versions.
Show answer
Complete the line so the function returns "no value".
optional< int > find ( int id) {
return ;
}
nullopt is the empty value for optional.
Check answer Show solution
What does optional<string> represent?
A A list of strings B A string that can't change C Either a string or nothing D A pointer to a string
It may or may not hold a value.
Show answer
optional< int > a;
optional< int > b = 7 ;
cout << a. value_or ( 1 ) + b. value_or ( 1 ) << endl ;
A 8 B 2 C 7 D An error
a is empty so gives 1; b holds 7.
Show answer
Which safely reads a string from variant<int, string> v without throwing?
A get<string>(v) B v.get() C *v D get_if<string>(&v)
get_if returns nullptr if the type doesn't match.
Show answer
When is optional a better choice than an exception?
A When a file is corrupted B When memory runs out C Never D When "no value" is a normal outcome, such as a search finding nothing
Exceptions are for genuine errors.
Show answer
Complete the code so main waits for the thread to finish.
thread t ( downloadFile) ;
t. ( ) ;
join blocks until the thread has finished.
Check answer Show solution
When does a std::thread start running its function?
A When you call start() B When you call join() C As soon as the thread object is created D When main ends
Creation starts the thread immediately.
Show answer
A Two threads finishing at the same time B A slow thread C A thread that never ends D Two threads accessing the same data at once, with at least one writing to it
It's undefined behaviour and must be prevented.
Show answer
A Locks a mutex when created and unlocks it automatically when destroyed B Creates a thread C Makes a variable atomic D Waits for all threads
It's RAII for locks.
Show answer
Four threads each increment an atomic<int> 1,000 times. What's the final value?
A Somewhere between 1,000 and 4,000 B Exactly 4,000 C 1,000 D It's undefined
Atomic increments can't be lost.
Show answer
The compiler sees a public function declaration, but the linker cannot find its definition. What should be checked?
A Whether making the declaration inline supplies a missing function body. B Whether including the header also compiles its implementation source. C The matching namespace/signature and whether its implementation source is linked. D Whether repeating the declaration in the caller supplies a definition.
A visible declaration enables compilation, while a matching linked definition supplies the implementation.
Show answer
A cast removes const from an object originally declared const. What happens if code writes through the result?
A The original declaration is automatically changed. B The compiler copies the object first. C Const is only advisory, so the write is always safe. D The modification has undefined behavior.
A cast changes an expression's qualification, not the permission to modify a genuinely const object.
Show answer
from_chars parses 12 from 12x without a conversion error. What additional check rejects this field?
A Whether the returned pointer reached the end of the input. B Whether the candidate is inside the numeric range without checking trailing text. C Whether the returned pointer is merely different from the starting pointer. D Whether the error code alone reports successful prefix conversion.
Full consumption distinguishes a whole-field parse from a valid prefix.
Show answer
A runtime grid row must be exposed safely. Which sequence fits?
A Compute an arbitrary pointer first and validate only after sorting. B Validate the row index, then create a bounded view into live contiguous storage. C Create a view with the row count as its element length. D Validate the row index against the total element count instead of the row count.
The view's preconditions and owner's lifetime must be established before access.
Show answer
A parsed code must remain valid after the input string is cleared. Which return type fits?
A A view into the input with an undocumented lifetime. B A reference to a local substring. C An owning string, optionally wrapped to represent parse failure. D A pointer into the parser's destroyed local buffer.
Owned output survives the source's destruction or mutation.
Show answer
An order must be identified after a vector is filtered and extended. Which design is robust?
A Keep the previous iterator and hope capacity is unchanged. B Keep the previous numeric position without reviewing shifts. C Compare the old pointer's address with new values. D Save its unique logical ID and perform a fresh lookup after mutation.
Logical identity survives storage and position changes, while borrowed handles may not.
Show answer
A compatible-allocator list node is spliced into another list. What should the caller remember?
A The node's identity remains, but its collection membership changes. B The node remains owned by both lists. C Its iterator must still be compared with the old list's end. D The saved iterator becomes a copy of the value.
Valid splice transfers the node while preserving applicable handles to that element.
Show answer
Two consumers share a queue. Which design prevents an empty-check race?
A Check empty outside synchronization and lock only during printing. B Coordinate the entire check-and-take transition or use a suitable concurrent queue. C Lock only the empty check and release the lock before taking the value. D Assume FIFO implies mutual exclusion.
Thread safety must protect the compound operation, not just one observation.
Show answer
A report must print unordered-map entries in alphabetic key order. Which design fits?
A Depend on the bucket order seen in one test run. B Reserve enough buckets and assume insertion order becomes a contract. C Build a snapshot and sort it under an explicit key comparison. D Choose a deterministic hash and assume its iteration order is alphabetic.
Presentation order must be established independently of unordered storage.
Show answer
A deadline expires at equality. Which test set establishes that rule?
A Comparing points from unrelated clocks. B A single sleep longer than the deadline. C Two checks after the deadline without checking equality. D Controlled points before, exactly at and after the deadline.
Deterministic boundary values directly test the inclusive expiration condition.
Show answer
A selector needs three distinct IDs from a unique bounded list. Which approach has a clear termination argument?
A Shuffle a copy and take a validated number of elements. B Seed an engine again for each selected ID. C Select from zero through size minus one without checking emptiness. D Draw forever until duplicates stop occurring.
Sampling from a shuffled unique list avoids duplicate element selection and validates the requested count.
Show answer
A friend reservation operation rejects insufficient stock. What should its test verify?
A Only that private access compiles. B That rejection leaves stock unchanged and success preserves nonnegative stock. C That a rejected request still subtracts the requested quantity. D That failure always sets stock to zero.
Privileged access must still preserve the domain's invariants.
Show answer
An invoice contains an address but is not substitutable for an address. Which relationship is usually clearer?
A Publicly inherit Address for convenient field reuse. B Virtually inherit every value type. C Store an Address member through composition. D Expose an implicit base conversion solely to avoid writing a getter.
Composition expresses owned parts without claiming an inappropriate is-a contract.
Show answer
Which step makes the worked update's commit argument sound?
A Append directly to live and validate only afterward. B Catch every error and report success. C Mark validation noexcept even though it throws. D Build a valid candidate first, then commit with a suitable nonthrowing swap.
Failures before commit leave the original unchanged, and the commit itself must not undermine that guarantee.
Show answer
The field writer only observes arguments. Which parameter contract is appropriate?
A Use typed const references and define the empty-pack behavior. B Accept untyped variadic arguments without type checking. C Store references indefinitely after returning. D Move every value unconditionally before output.
Observation needs no ownership transfer, and the variadic boundary still needs an explicit zero-argument rule.
Show answer
A type satisfies Reservable but returns true after subtracting too much stock. What follows?
A The concept automatically repairs the method. B The syntactic capability is satisfied, but the semantic contract is broken. C Removing runtime validation makes it conform. D Successful compilation proves the invariant.
Concepts do not prove arbitrary behavioral laws from a method signature.
Show answer
A predicate captures threshold by value, then the original variable changes. What happens?
A The predicate automatically reads the latest variable value. B The entire source becomes immutable. C The predicate keeps its captured threshold while still borrowing the live source. D The view converts into a snapshot automatically.
Predicate capture and source ownership are separate parts of the pipeline.
Show answer
A sanitizer build cannot link its runtime on the current platform. What should the report say?
A The program passed sanitizer verification. B The unsupported check proves no memory bugs exist. C The fixture should execute undefined behavior without instrumentation instead. D Sanitizer verification was unavailable; report the checks actually completed.
Tool configuration failure must not be presented as passing evidence.
Show answer
A new CTest executable links successfully. What establishes that its checks pass?
A Running the registered test and observing its actual status. B Successfully configuring the project without executing its tests. C Building the test target while assuming every runtime assertion must pass. D Assuming compilation proves runtime behavior.
Build success and test success are distinct verification stages.
Show answer
No exercises match those filters.