Multiple Definitions of -,* Symbols in C++ Primer and the Differences between int * P and int * P

Time:2019-10-4

&and*Such symbols can be used not only as operators in expressions, but also as part of declarations. The context of symbols determines the meaning of symbols:

int i = 42;
Int &r = i; //& follows the type name, so it is part of the declaration, and R is a reference
Int * p; //* appears next to the type name and is therefore part of the declaration, P being a pointer p
P= &i; //& appears in an expression and is an address fetch
* P = i; //* appears in an expression and is a dereference
Int &r2 = * p; //& is part of the declaration, * is a dereference

In the statement of declaration,&and*Used to compose composite types; in expressions, their roles are converted into operators. Although appearing in different scenarios

It’s the same symbol, but because of the different meanings, we can treat them as different symbols.

According to C++ Primer:

aboutint* pThe basic data type isintThe back*Actually, it’s a declarator. Different declarators can be used after a common set of data types. For example:

Int i = 1024, * P = &i, & R = i; / I is an int data, P is an int pointer, R is an int reference.

aboutint *pIts sumint* pThe same meaning is used for pointer variable p of type int.

But it’s easier to understand that declarers are followed by variable names. Otherwise, misleading phenomena may occur:

for example

Int * p1, p2; denotes that P1 is an int pointer and P2 is an int variable. Instead of p1, P2 are pointer variables, and they share the basic data type part.

If writtenint *p1,p2;It has exactly the same meaning as the previous expression, but it is clearer and will not lead to misleading.

However, for the use of the above two ways of writing, mainly depends on personal habits, but it is best not to mix.

summary

Above is the whole content of this article. I hope the content of this article has some reference value for your study or work. Thank you for your support to developpaer. If you want to know more about it, please check the links below.

Recommended Today

How to search files or directories under CentOS

Search for files or directories: The search for files is great! Because we often need to know where that file is, let’s talk about how to search it! There are also quite excellent ones under Linux Search system! Usually find is not very common! Because the speed is slow, but also very hard disk! Usually […]