Re: Why is "Hello World" const char* ?

From: CBFalconer (cbfalconer_at_yahoo.com)
Date: 02/06/05


Date: Sun, 06 Feb 2005 20:46:39 GMT

Ron Natalie wrote:
> Luke Wu wrote:
>
>> In C, a string literal (like "Hello") in value context (like the
>> right side of an assignment= operator) evaluates to a pointer
>> value of type (const char*) that points to the first character.
>
> Nope, it evaluates to an array of char, which converts to pointer
> to char. The characters are effectively const (it is undefined
> behvaior to attempt to change them), but the type of the
> expression is not const char*. (except when sizeof or & is
> applied to the array value).
>
> It's effectively the same in C++, except C++ defines a formal
> array-to-pointer conversion.

However it is advisable to declare such strings as:

  const char *foo = "foobar";

so that the C compiler can emit suitable warnings on misuse, such
as trying to alter it with such things as *foo = 'F'; Note that
foo = "barfoo"; is perfectly legal, except you may never find the
"foobar" string again.

-- 
"If you want to post a followup via groups.google.com, don't use
 the broken "Reply" link at the bottom of the article.  Click on 
 "show options" at the top of the article, then click on the 
 "Reply" at the bottom of the article headers." - Keith Thompson


Relevant Pages

  • Re: array -- foo, &foo and &foo[0]
    ... I think if we define foo as char array, for example, ... This pointer has type char*, ...
    (microsoft.public.vc.language)
  • Re: pointer usage in c
    ... > char *foo; ... I think my teacher wrong. ... Your array b is local to the function foo. ...
    (comp.lang.c)
  • Re: data types question
    ... >> data typing (among other things, you could cast something to a type ... 31-dimensional arrays of char, which is still impractical to list. ... debug_print_any_type(typeof(foo), foo) which could, for example, ... array elements if foo is an array) Given that you've got a "plug-in" ...
    (comp.lang.c)
  • Re: Why is "Hello World" const char* ?
    ... > Nope, it evaluates to an array of char, which converts to pointer ... > applied to the array value). ... foo = "barfoo"; is perfectly legal, except you may never find the ... the broken "Reply" link at the bottom of the article. ...
    (comp.lang.c)
  • Re: Questions about Delphi-down-versioning a project
    ... into array of char; ... bottom of the popup ...
    (alt.comp.lang.borland-delphi)