Codeforces celebrates 10 years! We are pleased to announce the crowdfunding-campaign. Congratulate us by the link https://codeforces.com/10years. ×

What to look for if the bug in your code disappear when you add debugging statement

Revision en1, by z4120, 2019-12-11 18:12:10

tl;dr:

If you want to try to figure it out, read below and don't open this

Recently I was writing some code that looks roughly like this:

double value= /* something */;
for(double step=1024;step>1e-8;step/=2)if(value-step>0){
	value-=step;
	// long long code to check condition satisfied
	if(not ok)
		value+=step;
}

While it gives correct answer locally on all sample test case, the result is wrong on Codeforces machine.

I had no idea what's going on, then decide to add a debug statement to the begin of the // long long code block. However, when I add anything there (even cout<<"";) the code gives the correct answer.

Initially I thought there's some undefined behavior, but I compiled with sanitization turned on, and there's no error reported.

Switching to another compiler works well on that particular test case.

Can you guess what could be the cause? (It's a bug in the code, not a compiler bug.)

(Of course if You're given the complete code and debug it for a while, you'll be able to find out the bug as well. The point here is that, can you guess what's the problem?)

Спойлер

Even if you knew about the behavior already (like me while debugging the code), I hope this blog can be useful to you when your code happen to have such a hard-to-explain behavior.

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English z4120 2019-12-11 18:12:10 2703 Initial revision (published)