Re: Is C++ a type-safe language ??

From: John Harrison (john_andronicus_at_hotmail.com)
Date: 07/06/04


Date: Tue, 06 Jul 2004 08:18:21 +0100


> Thats what I was pointing out: Here the expression fails because the
> type of 'p' is const char * and 'pc' is char *....so the compiler
> gives 'cannot convert from const char * to char *'. But why doesn't
> give in the following case ?
>
> char *str = "String Literal";
>
> Here also type of "String Literal" is const char * and type of str is
> char * !!

No it isn't, the type of "String Literal" is const char [15], it's an
array not a pointer.

The conversion of this array or const char to char* is explicitly allowed
by 4.2 paragraph 2 of the standard. It's purpose is compatibility with C.
In the very old days C did not have const and so code like your example
was commonplace.

Nevertheless it is an error to use this to modify a string literal.

One excemption from type safety rules for the purpose of bacwards
compatibility does not make C++ a non-type safe language. It is still more
type safe than any other language in common use (AFAIK).

john



Relevant Pages

  • Re: Controlling Static Data and Memory Organization...If Possible...
    ...   int value; ... with each successive entry into the static array. ... compilers and compiler options. ... const char name; ...
    (comp.lang.c)
  • Re: why is this assignment correct ?
    ... The C standard specifies that the type of a string literal is "array ... of char" and most specifically not "array of const char". ... to modify a string literal in C produces undefined behavior, ...
    (comp.lang.c)
  • Re: About Segmentation fault
    ... It's perfectly legal to modify non-constant array elements. ... Like all string literals in C, ... I never said "array of 6 const char". ...
    (comp.lang.c)
  • Re: Why is "Hello World" const char* ?
    ... > Your statement is incorrect. ... Since the first character is of type (const char) as ... > pointer to const char. ... The type of a string literal is "array of char", ...
    (comp.lang.cpp)
  • Re: Why is "Hello World" const char* ?
    ... > Your statement is incorrect. ... Since the first character is of type (const char) as ... > pointer to const char. ... The type of a string literal is "array of char", ...
    (comp.lang.c)