Why does c++ pointer * associate to the variable d

2019-02-16 05:13发布

问题:

Why was C++ designed such that the correct way to declare two int *s on the same line is

int *x, *y;

not

int* x,y;

I know some people think you should avoid either form and declare every variable on its own line, but I'm interested in why this language decision was made.

回答1:

To keep compatibility with C code, because that's how C works.

Bjarne makes a good point here:

The choice between int* p; and int *p; is not about right and wrong, but about style and emphasis. C emphasized expressions; declarations were often considered little more than a necessary evil. C++, on the other hand, has a heavy emphasis on types.

A typical C programmer writes int *p; and explains it *p is what is the int emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.

A typical C++ programmer writes int* p; and explains it p is a pointer to an int emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well.

So, the motivation for this working as this in C++ is how it works in C.

The motivation it works like that in C is that, as stated above, C emphasizes expressions rather than types.



回答2:

The simple answer is: because that's the way C does it. Which, of course, only begs the question: why does C do it this way?

The original philosophy, in early C, is that the declaration be an exact image of the use. So when you write:

int *p;

, you are declaring that the expression *p has type int (and the compiler works out the actual type of p accordingly).

This, of course, ceased to be true the day C introduced typedef, and later struct. And any resemblance disappeared completely with const (first introduced in C++, then retrofitted into C), where things like

int *const p;

have no relationship with use. But by then, the die was cast.



回答3:

Answer

That comes from "C" ( "plain c", "pure c", whatever ).

When a pointer variable is already declared, its used like this:

...
*p = &x;
*q = SomePointerFunc();
....

I read that the original inventors of "c" wanted programmers to declare pointers variables with the same syntax as they are used, with the star before the variable identifier:

...
int *p;
int *q;
...

The same goes for arrays:

...
x[5]  = 'a';
y[77] = SomeItemFunc();
...

...
char x[5];
int  y[100];
...

Some teachers that I had, insist to declare types for variables & functions this way (star close to identifier):

...
int *p;
int *q;
...

Instead of this (star next to type identifier):

...
int* p;
int* q;
...

Extra

In Java, and other languages, like C#, the declaration of arrays, or pointers are next to the type, leaving the variable or function identifier alone, like this pseudocode:

*int p;
*int q;
char[5] x;
int[100]  y;

I prefer this technique.

Cheers.