Chapter 142
HomeThe best bug fix is the bug that never happens. Defensive coding makes assumptions explicit and catches mistakes at runtime instead of in WA verdicts.
int arr[100]; int n; cin >> n; // if n > 100 → buffer overflow!
// Use vector instead of fixed arrays vectorarr(n); // dynamic, bounds-checked with .at() // Assertions for debug assert(n > 0 && "n must be positive"); assert(arr.size() == n); // const for invariants const int MOD = 1e9 + 7; // Structured bindings for clarity auto [min_val, max_val] = minmax_element(arr.begin(), arr.end()); // Early returns for edge cases if (arr.empty()) return 0; // Always use braces for (int x : arr) { total += x; } // not: for (...) total += x;