2

When running this code on Code Blocks breakpoint 2 occurs before breakpoint 1.

Breakpoint 1 eventually occurs followed by breakpoint 1 but just wondering why it occurs in the order 212

#include <bits/stdc++.h>
using namespace std;

void solve() {
    int n; cin >> n; // Breakpoint 1
    int monks[n];

    for(int i=0; i<n; i++){
        int a; cin >> a;
        monks[i] = a;
    }



    sort(monks, monks+n);


    int total = 0; // Breakpoint 2

}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    freopen("hirein.txt", "r", stdin);
    freopen("hireout.txt", "w", stdout);

    solve();

    return 0;
}
Xyrexy
  • 21
  • 4
  • 3
    [Why should I not #include ?](https://stackoverflow.com/q/31816095/7509065) – Joseph Sible-Reinstate Monica Jul 17 '20 at 01:32
  • 3
    [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/7509065) – Joseph Sible-Reinstate Monica Jul 17 '20 at 01:33
  • 7
    C++ compilers are allowed to perform any optimizations that have no observable effects. Initialing `total` to 0 has no observable effect in the shown code, in fact it does nothing whatsoever, and since doing nothing whatsoever can be done any time, the compiler chose to spew out the code that does nothing before the rest of the code. That's it. – Sam Varshavchik Jul 17 '20 at 01:33
  • Variable length array's are not standard – pvc Jul 17 '20 at 02:08
  • @SamVarshavchik Thanks bro that makes alot of sense, was just confusing me when debugging because my arrays were random – Xyrexy Jul 17 '20 at 05:39

1 Answers1

2

Breakpoint 2 is on an initialization. Breakpoint 1 is on code that must take place after at least some initialization is done. It's probably easiest to initialize all the variables at the same time. It's possible even a single memset-like operation is used to zero them all.

If all initialization takes place at the same time, then breakpoint 2 will occur before breakpoint 1.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278