String constification

Alexandre Julliard julliard at winehq.org
Mon Apr 26 13:55:49 CDT 2004


Francois Gouget <fgouget at free.fr> writes:

> On Sat, 24 Apr 2004, Dmitry Timoshkov wrote:
>
>> "Francois Gouget" <fgouget at free.fr> wrote:
>>
>> > We find the same issues with an added twist: now that we can use
>> > literals we can write things like:
>> >
>> >    const char* str = "String literal";
>> >
>> > However this is slightly different from:
>> >
>> >    static const char* str[] = "String literal";
>> >
>> > The difference is that in the first case sizeof(str) returns 4 (on 32
>> > bit machines<g>) while in the latter we get 15. Some of our code relies
>> > on this so care must be taken when converting the latter to the former.
>>
>> My understanding of this is that in the first case you declare a const
>> pointer and hope that a compiler is smart enough to place a pointed by
>> it object into a read only section, while in the second case you explicitly
>> say to a compiler to place the whole object into a read only section.
>
> In the first case you declare a const pointer and hope the compiler will
> place the string in a const section. In the second case you declare a
> const buffer and hope the compiler will put it in a read-only section.

The first case is not a const pointer, it's a pointer to a const
string, and it requires the compiler to allocate separate (writable)
storage for the pointer, so you are wasting 4 bytes per string. You
could use 'const char * const' to at least put the 4 bytes in
read-only storage, but unless there's a real need for a separate
pointer, using the buffer form is much preferable.

-- 
Alexandre Julliard
julliard at winehq.org



More information about the wine-devel mailing list