[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: OT: Language War (Re: "C" Manual)



Richard Cobbe wrote:

> C:
>     int x;
> 
>     x = "foo";
> 
> You'll get a type error here at compile time, for obvious reasons.
> Question: how can this be a type error if only variables have types?
> You need to realize that "foo" has type (const) char * before you can
> determine that you can't assign it to an int.

"foo" isn't a pointer to char (char*); it's an array of char (char[]).
Consider:

    int main()
    {
        char* p = "foobar";

        printf("sizeof pointer = %d\n", sizeof(p));
        printf("sizeof array   = %d\n", sizeof("foobar"));

        return 0;
    }

This produces the following output:

    sizeof pointer = 4
    sizeof array   = 7

(The array has size 7 because the string literal automatically gets a
null appended to its six elements.)

This is a nitpicky point, and not one which invalidates the rest of your
argument, but it is a common error of novice C programmers not to
understand the difference between arrays and pointers (which the
language makes confusing by passing arrays by reference and allowing the
array-index operator to be applied to pointers), so when this sort of
thing pops up, I like to point it out.

Craig

Attachment: pgpdQkgyzBCj0.pgp
Description: PGP signature


Reply to: