C Programming · Interview question

Why might code work at -O0 but break at -O2?

A strong answer

It's the signature of undefined behavior. At -O0 the compiler does minimal optimization and mostly emits straightforward instructions, so UB often happens to yield the "expected" result, a signed overflow just wraps on the hardware, an uninitialized variable happens to hold a usable value. At -O2 the optimizer aggressively applies its "UB cannot happen" assumption: it might conclude a condition is always true (because the alternative would require signed overflow), eliminate a null check (because you already dereferenced the pointer, so it "must" be non-null), or reorder/remove code in ways that expose the latent bug. Same source, different machine code, different behavior, because the program was never valid C to begin with. The takeaway is that passing at -O0 or in a debug build is no evidence of correctness; you need sanitizers and clean warnings.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Undefined Behavior & Pitfalls

Why code that works at -O0 breaks at -O2: what undefined behavior is, the catalog of UB every firmware engineer must recognize, and how sanitizers catch it.

More Undefined Behavior & Pitfalls questions

Browse all 472 interview questions
Why might code work at -O0 but break at -O2? | EmbeddedPrep.io