Commenting a cout statement appears to change variable value

I wrote some code similar to the one below, and I am unable to explain its output:

#include <iostream>
#include <cmath>
using std::cout, std::endl;

int f(int n)
{
    int ans = cbrt(n);
    cout<<ans<<endl;//<- the statement of interest
    return ans;
}

int main() 
{    
    int result = f(3375);
    cout<<"f(3375) = "<<result<<endl;
	
	return 0;
}

This code gives me the output:

14
f(3375) = 14

However, if I comment the statement cout<<ans<<endl; then the output is

f(3375) = 15

This behaviour was observed while using the codechef compiler, and I was unable to replicate it on other compilers. Why does commenting the cout statement affect the value of ans?

This is another example of the confusing floating point error. When you try to use the following code, You will be surprised to find that the answer is actually 14.99999999999999998223643160599750, not 15.0

#include <iostream>
#include <cmath>
using std::cout, std::endl;

float f(int n)
{
    printf("%.30f\n",cbrt(n));
    int ans = cbrt(n);
    // cout<<ans<<endl;//<- the statement of interest
    return ans;
}

int main() 
{    
    float result = f(3375);
    cout<<"f(3375) = "<<result<<endl;
	
	return 0;
}

After outputting this line, the result will be 14. I suspect the reason for this is that Codechef’s cbrt implementation does not adhere to the C++ specification, and when you call it directly and return int
type, the C++ optimization system catches it and realizes that the goal of the function is to open the root of the third square. So call __builtin_crbtl() directly. this function returns the correct result. When you output ans, the function is not equivalent to calc cube, so you call the incorrectly implemented cmath::crbt, which gives less than a floating-point error and is rounded to output 14.

This is absolutely not my area of expertise, but a little testing leads me to believe that you’re right and it’s implementation-dependent (and more specifically, perhaps even platform-specific implementation-dependent).

I tried running the code on my system, and also on Codechef, Codeforces, and Atcoder’s custom invocations.
Of those 4, only codeforces outputs 15 in both cases; the other three output 14 and 15 with/without the line commented out.
The common thread here is that, afaik, Codeforces runs on Windows while the other three use linux (my system does, at least).

It’s also definitely an optimization thing: locally, compiling with O0 makes both versions output 14 while O2 gives the results you described.
Most online judges compile with O2 by default.