Multiple definitions of symbols * in C++ Primer and differences between int *p and int* p

  • 2020-06-15 09:56:17
  • OfStack

& and * Such a symbol can be used as an operator in an expression or as part 1 of a declaration. The context of the symbol determines the meaning of the symbol:


int i = 42;
int &r = i;    //& It follows the type name and is therefore declared 1 Part, r is 1 A reference 
int *p;       //* It follows the type name and is therefore declared 1 Part of the ,p is 1 A pointer to the p
p = &i;      //& It appears in the expression, yes 1 A fetching address character 
*p = i;       //* It appears in the expression, yes 1 A dereference 
int &r2 = *p;  //& Is the statement 1 Part, * is 1 A dereference 

In the statement declared, & and * Used to form compound types; In expressions, their role becomes operator. In different scenarios, though

It's the same symbol, but it has very different meanings, so we can think of them as different symbols.

According to C++Primer:

for int* p (This is legal, but misleading), the basic data type is int Behind, * It's actually a declarator. You can use different declarators after a common set of data types. Such as:

[

int i =1024, *p = & i, & r = i; //i is 1 int type data, p is 1 int type pointer, and r is 1 int type reference.

]

for int *p , and int* p Represents the pointer variable p of type int.

But it is easier to follow the declaration with the variable name. Otherwise, it may be misleading:

For example,

[

int * p1 p2; The implication is that p1 is a pointer to an int type and p2 is a variable of TYPE int. Instead of p1,p2 are pointer variables that share the basic data type part.

]

If written int *p1,p2; Then, it has the same meaning as the above expression, but it is clearer and will not mislead.

However to the use of above two kinds of writing method, basically see individual habit, but had better not mix.

conclusion


Related articles: