Question 4
Back to Exercise
What is the output of the following C++ program? (The program is free of data races, so its output is the same on every run.)
#include <atomic>
#include <iostream>
int main() {
std::atomic<int> n{10};
int a = n.fetch_add(5); // returns the OLD value
int b = ++n; // returns the NEW value
int c = n.exchange(100); // sets 100, returns the old value
int expected = 100;
bool swapped = n.compare_exchange_strong(expected, 7);
std::cout << a << ' ' << b << ' ' << c << ' ' << swapped << ' ' << n << '\n';
return 0;
}
- A 10 16 16 1 7 Correct
- B 15 16 16 1 7
- C 10 16 100 1 7
- D 10 16 16 0 100
Correct Answer: Option A
fetch_add returns the value before adding; prefix ++ the value after. compare_exchange succeeds because n equals expected (100).
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!