Expert · Competitive programming, interviews and careers · topic 40 of 42 · 25 min
Classic C++ pitfalls in contests and coding rounds
Explanation
Why a pitfalls list?
C++ trusts the programmer and rarely stops you at run time. A small slip often gives a plausible but wrong answer, not a crash. Checking this list before submitting catches most of these silent errors.
1. Integer overflow
int a = 100000, b = 100000;
long long bad = a * b; // overflow: a * b is computed in int first
long long good = 1LL * a * b; // 10000000000
// Sum of 2 × 10^5 values up to 10^9 needs long long (up to 2 × 10^14).2. Unsigned size()
vector<int> v; // empty
for (int i = 0; i < v.size() - 1; ++i) { } // v.size() - 1 wraps to a huge number!
for (int i = 0; i + 1 < (int)v.size(); ++i) { } // safe3. Uninitialised variables and arrays
Local variables are not zeroed. int cnt; cnt++; is undefined. Global arrays ARE zero-initialised, which is why contest code often declares big arrays globally. When you reuse an array across test cases, reset it for each test, or you get WA on test case 2 onwards.
4. Out-of-bounds access
a[n] on an array of size n reads past the end silently. Off-by-one errors in loops and DP tables (dp[i - 1] when i is 0) are common. During practice, compile with -fsanitize=address,undefined -D_GLIBCXX_DEBUG to catch them with a clear message.
5. Slow input and output
- Use ios::sync_with_stdio(false); cin.tie(nullptr); at the start of main.
- Print '\n', not endl, inside loops: endl flushes every line, which can turn a 0.2 s program into a TLE with 10^6 lines of output.
- Do not mix printf/scanf with cin/cout after turning off sync.
6. Deep recursion
A DFS on a path-shaped graph with 10^5 or 10^6 nodes recurses that deep. With small stacks (1 MB on Windows by default) this crashes as a Runtime Error. Use an explicit stack (iterative DFS) or BFS when the depth can be large.
7. Floating-point comparison
double x = 0.1 + 0.2;
if (x == 0.3) { } // false!
const double EPS = 1e-9;
if (fabs(x - 0.3) < EPS) { } // true
// Better: avoid doubles when you can (use integers, e.g. paise, or compare a*d with b*c for fractions).8. Hash maps under attack and other traps
- On Codeforces, unordered_map with int keys can be made slow by anti-hash tests; use map or a custom hash with a random seed if you see TLE.
- Using map[key] to "check" inserts the key (and changes size()).
- Modular arithmetic: (a - b) % MOD can be negative in C++; write ((a - b) % MOD + MOD) % MOD.
- Integer division rounds toward zero: -7 / 2 is -3, not -4.
- 1 << 40 overflows int; write 1LL << 40.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Classic C++ pitfalls in contests and coding rounds · 1/6
Most wrong answers in C plus plus come from a short list of silent traps.
Prefer a video by a teacher? Find free videos on “common mistakes competitive programming c++ overflow long long endl” on YouTube ↗
In real life: The WA on test 12
A student's solution for "maximum subarray sum" passes 11 tests and fails test 12. The cause: the array has 2 × 10^5 values of 10^9, and the running sum was an int. Changing two variables to long long gives Accepted. This exact story repeats every day on every contest site.
long long best = LLONG_MIN, cur = 0; // was int: overflowed on big tests
for (long long x : a) {
cur = max(x, cur + x); // Kadane's algorithm
best = max(best, cur);
}
cout << best << '\n';Practice (0/4 done)
int a = 50000; int b = 50000; long long c = a * b; What is wrong?
What is -7 % 3 in C++?
vector<int> v; What does v.size() - 1 evaluate to?
Start a personal C++ "pre-submit checklist" file. Include at least 8 checks from this topic in your own words, and for the next 10 problems you solve, tick it before each submission. Note any WA it would have prevented.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- C++ interview questions and how to answer themCompetitive programming, interviews and careers · same module
- Data types and their sizesC Programming (from zero to systems) · Getting started with C
- Type conversion and castingC Programming (from zero to systems) · Operators and control flow
- Scalar types: numbers, bool and charRust Programming · Types, control flow and functions
- Recursion: functions that call themselvesData Structures and Algorithms (DSA) for interviews · Recursion and backtracking
- RecursionC Programming (from zero to systems) · Functions and arrays
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Why can endl cause TLE when printing 10^6 lines?
Answer: endl flushes the output every time, which is slow
Use '\n' and let the stream flush once at the end.
How should you compute (a - b) mod M safely when a and b are already reduced mod M?
Answer: ((a - b) % M + M) % M
Adding M makes the result non-negative.
A recursive DFS crashes on a straight-line graph with 10^6 nodes. Why?
Answer: The recursion is 10^6 calls deep and overflows the stack
Use an iterative DFS with an explicit stack, or BFS.
Which flag combination helps catch out-of-bounds and undefined behaviour while practising with GCC?
Answer: -fsanitize=address,undefined -D_GLIBCXX_DEBUG
Sanitizers and the debug STL report errors at the faulty line.
What makes dynamic programming faster than plain recursion for problems like Fibonacci?Related
Answer: Each sub-problem's answer is stored and reused instead of recomputed
Overlapping sub-problems are solved once.
Which printf format prints a size_t?Related
Why can comparing an int with a size_t be dangerous?Related
Answer: A negative int is converted to a huge unsigned value
Signed/unsigned comparison.
What happens on integer overflow in a debug build?Related
Answer: The program panics
Debug builds check for overflow at run time and panic.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Competitive programming, interviews and careers” before its exam: C++ interview questions and how to answer them, Careers with C++ and your next steps.
- Module 10 exam: Contests, interviews and careers · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
- 42 topics left in the course before the final exam.