Home > Backend Development > C++ > Where Should the Asterisk Go in C Pointer Declarations?

Where Should the Asterisk Go in C Pointer Declarations?

Mary-Kate Olsen
Release: 2024-12-28 11:53:16
Original
329 people have browsed it

Where Should the Asterisk Go in C   Pointer Declarations?

Pointer Placement in Declarations

In pointer declarations, the placement of the asterisk can be a source of confusion. Let's delve into the examples provided to understand the nuances of pointer placement.

Example 1-3:

int* test;
int *test;
int * test;
Copy after login

In these cases, test is declared as a pointer to an int. The asterisk modifies the base type, int, to indicate that test is a pointer rather than an int itself.

Example 4-6:

int* test,test2;
int *test,test2;
int * test,test2;
Copy after login

Case 4: Both test and test2 are pointers to an int. The asterisk applies to both identifiers, as there is no comma separating them.

Case 5 and 6: Only test is a pointer to an int, while test2 is a plain int. The comma separates the two identifiers, indicating that they are distinct declarations.

To avoid confusion, it's generally recommended to place the asterisk immediately before the identifier it modifies. This eliminates ambiguity and ensures that the pointer nature of the variable is clear.

For example:

int* test;  // test is a pointer to an int
int* test2; // test2 is a pointer to an int
Copy after login

Or, for added clarity, the following declaration can be used:

int *test, *test2;  // both test and test2 are pointers to an int
Copy after login

The above is the detailed content of Where Should the Asterisk Go in C Pointer Declarations?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template