The behaviour when dereferencing an invalid pointer is undefined. So I can only speculate on the underlying reason: it probably has to do with how and where stack variables are allocated, e.g. sequential function calls within a given scope might allocate stack variables from the same starting place, so stuff that's stack-allocated in the first call to cout << is likely to overwrite anything that was stack allocated on the prior call to treble. When it's done all in one call to cout <<, the value is fetched back before calling any other function, and thus before it's likely for it to have been overwritten, and it appears to work ok.
You can occasionaly predict how the thing is going to behave, e.g., I was pretty sure that this would happen:
double num = 5.0;
double* ptr = 0;
ptr = treble(num);
treble( 2.0 );
cout << endl << "Three times num = " << 3.0*num << endl << "Result = " << *ptr;
Outputs:
Three times num = 15
Result = 6
On my machine, but I wouldn't bet on it being the same as yours, and I'd never rely on it working like that on mine.
A clearer example:
#include <iostream>
int fn_a ( void )
{
int a = 0;
std::cerr << &a << std::endl;
}
int fn_b ( void )
{
int b = 0;
std::cerr << &b << std::endl;
}
int main ( void )
{
fn_a ( );
fn_b ( );
return EXIT_SUCCESS;
}
Outputs:
0xbff36764
0xbff36764
E.g. both function calls allocated a temporary variable in the same place, on my machine, today. (emphasis: "don't ever rely on this")
The important question, why are you doing this anyway?
double treble(double data)
{
double result = 0.0;
result = 3.0*data;
return result;
}
Is much more normal and safe.