Sujet : Re: No warning at implicit removal of const. Was: relearning C: why does an in-place change to a char* segfault?
De : richard (at) *nospam* damon-family.org (Richard Damon)
Groupes : comp.lang.cDate : 02. Aug 2024, 19:42:08
Autres entêtes
Organisation : i2pn2 (i2pn.org)
Message-ID : <82cc9501de86336cdef9fe610bce8e75238fb679@i2pn2.org>
References : 1 2 3 4 5 6 7
User-Agent : Mozilla Thunderbird
On 8/2/24 2:24 PM, Keith Thompson wrote:
Richard Harnden <richard.nospam@gmail.invalid> writes:
[...]
Is there any reason not to always write ...
>
static const char *s = "hello, world";
>
... ?
>
You get all the warnings for free that way.
The "static", if this is at block scope, specifies that the pointer
object, not the array object, has static storage duration. If it's at
file scope it specifies that the name "s" is not visible to other
translation units. Either way, use it if that's what you want, don't
use it if it isn't.
There's no good reason not to use "const". (If string literal objects
were const, you'd have to use "const" here.)
If you also want the pointer to be const, you can write:
const char *const s = "hello, world";
The one good reason to not make it const is that if you are passing it to functions that take (non-const) char* parameters that don't actually change that parameters contents.
These may still exist in legacy code since so far nothing has required them to change.
Perhaps it is getting to the point that the language needs to abandon support for that ancient code, and force "const correctness" (which I admit some will call const-pollution) onto code, first with a formal deprecation period, where implementations are strongly suggested to make the violation of the rule a warning, and then later changing the type of string constants.
Of course, implementations would still be free to accept such code, and maybe even not even warn about it in non-pedantic mode, but making it part of the Standard would be a step to cleaning this up.