Path: ...!weretis.net!feeder8.news.weretis.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson 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: Sun, 25 Aug 2024 14:26:59 -0700 Organization: None to speak of Lines: 35 Message-ID: <875xrofg4c.fsf@nosuchdomain.example.com> References: <20240801174026.00002cda@yahoo.com> <87zfpvfdk4.fsf@nosuchdomain.example.com> MIME-Version: 1.0 Content-Type: text/plain Injection-Date: Sun, 25 Aug 2024 23:27:00 +0200 (CEST) Injection-Info: dont-email.me; posting-host="40ee2afb4f283fffad3dfce85eeabfde"; logging-data="2207701"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/klCrD9JXGEb1FuofcBAP0" User-Agent: Gnus/5.13 (Gnus v5.13) Cancel-Lock: sha1:Zuwctdz+V0UXtxQytokzMzRDgCY= sha1:+MjvkBn8M7fhHKffLQjcHb6tZoM= Bytes: 2484 dave_thompson_2@comcast.net writes: > On Fri, 2 Aug 2024 13:04:55 +0100, Richard Harnden > 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 */