so what exactly is const supposed to mean?

Sean Kelly sean at f4.ca
Tue Jul 4 09:28:39 PDT 2006


Bruno Medeiros wrote:
> Sean Kelly wrote:
>> Bruno Medeiros wrote:
>>>
>>> There is a slight difference from D's const and a const that places 
>>> the data in ROM as you cannot get the address of a D const var (it's 
>>> not an lvalue).
>>
>> Ever tried taking the address of a const string?  That you can't take 
>> the address of other const types is simply a result of optimization.
>>
> 
> I tried it now, and the const string also can't be taken an address from:
> 
>   const char[] str = "ABC";
> 
>   void func()
>   {
>     *(&str) = "123"; // : "ABC" is not an lvalue
>   }

That's interesting.  I would have expected all strings to live in a 
static data segment.  And in fact they seem to, though initialization 
seems to happen in a slightly weird manner:

     const char[] str = "ABC";

     void main()
     {
         printf( "%.*s\n", str );
     }

generates:

     _DATA   segment
             db      041h,042h,043h,000h,000h,000h,000h,000h
     _D4test3strAa:
             db      003h,000h,000h,000h
             dd      offset FLAT:_DATA
             db      041h,042h,043h,000h,000h,000h,000h,000h
             db      003h,000h,000h,000h
             dd      offset FLAT:_D4test3strAa[8]
             db      025h,02eh,02ah,073h,00ah,000h
     _DATA   ends
     CONST   segment
     CONST   ends
     _BSS    segment
     _BSS    ends
     __Dmain comdat
             assume  CS:__Dmain
     L0:             push    dword ptr _D4test3strAa[014h]
                     push    dword ptr _D4test3strAa[010h]
                     push    offset FLAT:_D4test3strAa[018h]
                     call    near ptr _printf
                     xor     EAX,EAX
                     add     ESP,0Ch
                     ret
     __Dmain ends

Notice that "041h,042h,043h" exists both by itself as a literal and 
within the static initializer for 'str'.  Notice also that 'str' does 
indeed live within a static data segment.  I'm not entirely certain why 
the literal isn't optimized away, however, as it's only ever used for 
initializing 'str'.


Sean



More information about the Digitalmars-d-learn mailing list