Groups | Search | Server Info | Login | Register
Groups > comp.lang.c > #387779
| From | Keith Thompson <Keith.S.Thompson+u@gmail.com> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: No warning at implicit removal of const. Was: relearning C: why does an in-place change to a char* segfault? |
| Date | 2024-08-25 14:26 -0700 |
| Organization | None to speak of |
| Message-ID | <875xrofg4c.fsf@nosuchdomain.example.com> (permalink) |
| References | (2 earlier) <v8gi7i$29iu1$1@dont-email.me> <slrnvaorkl.34j6.candycanearter07@candydeb.host.invalid> <87zfpvfdk4.fsf@nosuchdomain.example.com> <v8ii17$2q5p1$1@dont-email.me> <ka6ncjp0ca2dvf6v6lbg6faindvgmujtoa@4ax.com> |
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.com
void Void(void) { Void(); } /* The recursive call of the void */
Back to comp.lang.c | Previous | Next — Previous in thread | Find similar
Re: No warning at implicit removal of const. Was: relearning C: why does an in-place change to a char* segfault? dave_thompson_2@comcast.net - 2024-08-25 16:52 -0400 Re: No warning at implicit removal of const. Was: relearning C: why does an in-place change to a char* segfault? Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2024-08-25 14:26 -0700
csiph-web