Sujet : Re: No warning at implicit removal of const. Was: relearning C: why does an in-place change to a char* segfault?
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 25. Aug 2024, 22:26:59
Autres entêtes
Organisation : None to speak of
Message-ID : <875xrofg4c.fsf@nosuchdomain.example.com>
References : 1 2 3 4 5 6 7
User-Agent : Gnus/5.13 (Gnus v5.13)
dave_thompson_2@comcast.net writes:
On Fri, 2 Aug 2024 13:04:55 +0100, Richard Harnden
<richard.nospam@gmail.invalid> wrote:
>
[string literals not typed const in C even though writing prohibited]
>
Is there any reason not to always write ...
static const char *s = "hello, world";
... ?
You get all the warnings for free that way.
>
But sizeof s is 8 or 4 regardless of the string, while sizeof "some
string" is the length of the string plus 1 (for the null terminator).
>
static const char s[] = "hello, world";
// autosized by initializer
>
would be a better replacement, or in C99+ if at file scope
>
(const char[]){"hello, world"}
Most uses of that string are very likely to be via function arguments.
If it's defined at file scope, defining s as an array rather than as a
pointer can be useful for any code that refers to it directly (and needs
its size), but as soon as you pass it to a function you lose the size
information (and probably need to pass an extra argument for the
length).
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */