Topic: String literal pointer decay funkiness...


Author: Frederick Gotham <fgothamNO@SPAM.com>
Date: Tue, 3 Oct 2006 15:08:03 CST
Raw View
The type of a string literal is:

    char const[sizeof "whatever is written"]

However, it decays to a pointer to non-const, rather than a pointer to const.

Here's some funky code:

    void Func(char*) {}
    void Func(char const*) {}

    int main()
    {
        Func("Hello");
    }

I would have thought that the "char*" version would be invoked, but it seems
that at least one modern compiler invokes the "char const*" version.

Any thoughts?

--

Frederick Gotham

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]





Author: ron@spamcop.net (Ron Natalie)
Date: Tue, 3 Oct 2006 21:40:51 GMT
Raw View
Frederick Gotham wrote:
> The type of a string literal is:
>=20
>     char const[sizeof "whatever is written"]

This is true.

 > However, it decays to a pointer to non-const, rather than a pointer=20
to const.

This is not true:

A string literal (2.13.4) that is not a wide string literal can be=20
converted to an rvalue of type =93pointer to
char=94; a wide string literal can be converted to an rvalue of type=20
=93pointer to wchar_t=94. In either case,
the result is a pointer to the first element of the array. This=20
conversion is considered only when there is an
explicit appropriate pointer target type, and not when there is a=20
general need to convert from an lvalue to an
rvalue. [Note: this conversion is deprecated. See Annex D. ] For the=20
purpose of ranking in overload resolution
(13.3.3.1.1), this conversion is considered an array-to-pointer=20
conversion followed by a qualification
conversion (4.4). [Example: "abc" is converted to =93pointer to const=20
char=94 as an array-to-pointer conversion,
and then to =93pointer to char=94 as a qualification conversion. ]


> I would have thought that the "char*" version would be invoked, but it =
seems=20
> that at least one modern compiler invokes the "char const*" version.
>=20
Why would you expect that?   While the conversion to char* is permitted,=20
the type is still char const[n] which would match preferentially the
char const* overload.

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]