Why is the dereference operator (*) also used to declare a pointer?

前端 未结 6 875
一向
一向 2021-01-30 12:27

I\'m not sure if this is a proper programming question, but it\'s something that has always bothered me, and I wonder if I\'m the only one.

When initially learning C++,

6条回答
  •  再見小時候
    2021-01-30 13:23

    Because the committee, and those that developed C++ in the decades before its standardisation, decided that * should retain its original three meanings:

    • A pointer type
    • The dereference operator
    • Multiplication

    You're right to suggest that the multiple meanings of * (and, similarly, &) are confusing. I've been of the opinion for some years that it they are a significant barrier to understanding for language newcomers.


    Why not choose another symbol for C++?

    Backwards-compatibility is the root cause... best to re-use existing symbols in a new context than to break C programs by translating previously-not-operators into new meanings.


    Why not choose another symbol for C?

    It's impossible to know for sure, but there are several arguments that can be — and have been — made. Foremost is the idea that:

    when [an] identifier appears in an expression of the same form as the declarator, it yields an object of the specified type. {K&R, p216}

    This is also why C programmers tend to[citation needed] prefer aligning their asterisks to the right rather than to the left, i.e.:

    int *ptr1; // roughly C-style
    int* ptr2; // roughly C++-style
    

    though both varieties are found in programs of both languages, varyingly.

提交回复
热议问题