I am new to C++. When I debugged in Clion, I found that the execution order using Step over (F8) doesn't match the real code's order. So far, I think the most possible reason is compiler optimization. I have no impression that I've enabled this and I am using LLDB to debug.
It seems related to this answer: Why don't my breakpoints run in order? GCC and C
Here is my code:
int depthSum(vector<NestedInteger> &nestedList) {
deque<pair<int, NestedInteger>> q;
int level = 1;
for (NestedInteger n : nestedList) {
q.push_back({ level, n});
}
int res = 0;
while (!q.empty()) {
auto pair = q.front();
q.pop_front();
if (pair.second.isInteger()) {
level--;
res = (level * (pair.second.getInteger()));
cout << res << endl;
} else {
level++;
for (NestedInteger nestedInteger : pair.second.getList()) {
q.push_front({level, nestedInteger});
}
}
}
return res;
}
When the breakpoint step at the res = (level * (pair.second.getInteger()));
and then press the F8 it jumps back to the level--
, and then press F8 jump to the res = (level * (pair.second.getInteger()));
, once again press F8 that will jump to the cout << res << endl;
Is this really because code reordering? By the way, the result of the code logical without error though debugging order not match expectation, but I have not found some open code optimization option in my project.
I tried to avoid optimization but problem still exists.
---------------------------- updated
This is working, but I have no clue why -O0 is not working. Logically speaking -O0 should be working because this avoids all optimization.
-DCMAKE_C_FLAGS_DEBUG:STRING="-g -O1" -DCMAKE_CXX_FLAGS_DEBUG:STRING="-g -O1"
you're IDE probably is in release mode configuration ... so change it to debug mode