Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #120449

Re: literal string type

From Keith Thompson <kst-u@mib.org>
Newsgroups comp.lang.c
Subject Re: literal string type
Date 2017-09-28 09:08 -0700
Organization None to speak of
Message-ID <lnefqqyfdx.fsf@kst-u.example.com> (permalink)
References <150a364a-68b1-4c35-9d34-e94bbf115d23@googlegroups.com>

Show all headers | View raw


Thiago Adams <thiago.adams@gmail.com> writes:
> This sample:
>
> void F(char * s) {
> }
>
> int main() {
>     F("a");
>     return 0;
> }
> 
> Compiles with zero warnings.

("int main(void)" is preferred.)

The string literal "a" is of type `char [2]`, which is implicitly
converted to `char*`.  Logically it would be better for it to be of type
`const char[2]`, which would be converted to `const char*`, but it
remains non-const for compatility with pre-ANSI C code (when "const"
didn't exist).  (C++ did make this change; a C++ compiler would
diagnose, and perhaps reject, the above code.)

> But this one:
>
> void F(char * s) {}
>
> int main()
> {
>     const char s[2] = "a";
>     F(s);
>     
>     return 0;
> }
>
> give us:
>
> main.c:7:7: warning: passing argument 1 of ‘F’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
>      F(s);
>        ^

"a" is still of type `char[2]`, and it's used to initialze an object s
of type `const char[2]`, which converts to `const char*`.  By not using
"const" on its parameter declaration, F() threatens to modify the data
pointed to by the argument.

> Any ideas why the first sample doesn't have warnings?
> I have seen this in more than one compiler.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

Back to comp.lang.c | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

literal string type Thiago Adams <thiago.adams@gmail.com> - 2017-09-28 07:41 -0700
  Re: literal string type Malcolm McLean <malcolm.arthur.mclean@gmail.com> - 2017-09-28 07:50 -0700
    Re: literal string type Ben Bacarisse <ben.usenet@bsb.me.uk> - 2017-09-28 19:12 +0100
  Re: literal string type Keith Thompson <kst-u@mib.org> - 2017-09-28 09:08 -0700
    Re: literal string type Thiago Adams <thiago.adams@gmail.com> - 2017-09-28 10:19 -0700
      Re: literal string type Keith Thompson <kst-u@mib.org> - 2017-09-28 11:06 -0700
        Re: literal string type Thiago Adams <thiago.adams@gmail.com> - 2017-09-28 11:41 -0700

csiph-web