Skip to content

Expert · Competitive programming, interviews and careers · topic 40 of 42 · 25 min

Classic C++ pitfalls in contests and coding rounds

Explanation

Most Wrong Answers in C++ come from a few traps: integer overflow, wrong use of unsigned size(), uninitialised variables, reading outside arrays, slow I/O with endl, deep recursion, and comparing floating-point numbers with ==. Knowing them saves hours.

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

cpp
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).
If any intermediate value can pass about 2.1 × 10^9, use long long for it.

2. Unsigned size()

cpp
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) { }   // safe
size() returns an unsigned type. 0 - 1 in unsigned arithmetic becomes 18446744073709551615 on 64-bit systems. C++20 also has std::ssize(v), which returns a signed size.

3. 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

cpp
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).
Doubles cannot represent most decimals exactly.

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.
Think of it like this: This list is like a pilot's pre-flight checklist. Experienced pilots still read it every time, because the dangerous mistakes are small, silent and easy to forget under time pressure.
Tip: Keep a personal "mistakes log". Every time you get a WA, write the cause in one line. After a month you will see your own top three traps, and you will stop making them.

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

C++ pitfalls

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.

cpp
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';
Kadane's algorithm in O(n), with the overflow fixed.

Practice (0/4 done)

Task 1 · Question

int a = 50000; int b = 50000; long long c = a * b; What is wrong?

Task 2 · Question

What is -7 % 3 in C++?

Task 3 · Question

vector<int> v; What does v.size() - 1 evaluate to?

Task 4 · Practice

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

Question 1

1.Why can endl cause TLE when printing 10^6 lines?

Question 2

2.How should you compute (a - b) mod M safely when a and b are already reduced mod M?

Question 3

3.A recursive DFS crashes on a straight-line graph with 10^6 nodes. Why?

Question 4

4.Which flag combination helps catch out-of-bounds and undefined behaviour while practising with GCC?

Read more (free)

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.

From Core DSA patterns in C++

Which printf format prints a size_t?Related

Answer: %zu

%zu (C99).

From Data types and their sizes

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.

From Type conversion and casting

What happens on integer overflow in a debug build?Related

Answer: The program panics

Debug builds check for overflow at run time and panic.

From Scalar types: numbers, bool and char

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

  1. 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.
  2. Module 10 exam: Contests, interviews and careers · 12 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. 42 topics left in the course before the final exam.

← Previous: Core DSA patterns in C++