Optimizing Immutable and Purity

Walter Bright newshound1 at digitalmars.com
Wed Dec 24 11:11:58 PST 2008

Andrei Alexandrescu wrote:
> Walter Bright wrote:
>> Andrei Alexandrescu wrote:
>>>>> Const is still useful because inside a function you know for sure 
>>>>> that another thread can't modify the data.
>>>> I think you meant immutable.
>>> I meant const.
>> In the future, of course, "shared const" means another thread can 
>> modify it, but "const" means it cannot. Is that what you meant?
> Here's an example:
> int foo(const int*);
> void bar() {
>     int a = 5;
>     foo(&a);
>     // can assume a is unmodified?
> }
> There are two issues here. One is that the const guarantees that foo 
> does not legally change a, so it is useful for an optimization (e.g. 
> assume that a == 5 after the call to foo). The second issue is that 
> compilers often assume that a function call may change the stack of the 
> caller in an arbitrary way. I think it is safe to lift that assumption 
> for D programs and consider a functions' automatic variables as private 
> to the function.

I see what you mean, now. I thought you were talking about inside foo(). 
You're right that as far as bar() goes, foo() will not change a.

C and C++ optimizers assume that for locals which never have their 
address taken, function calls will not change them. This assumption must 
be valid otherwise locals could never be assigned to registers. If the 
address is taken, it must be assumed that calling a function will modify 

More information about the Digitalmars-d mailing list