Home >Backend Development >C++ >Where Should the Asterisk Go When Declaring Pointers in C/C ?

Where Should the Asterisk Go When Declaring Pointers in C/C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 04:33:12575browse

Where Should the Asterisk Go When Declaring Pointers in C/C  ?

Pointer Declaration in C/C : Placement of Asterisk

In C/C , there are two distinct notations for declaring pointer variables:

  • Notation (a): char* p;
  • Notation (b): char *p;

The placement of the asterisk (*) in these notations has been a subject of debate among programmers.

Rational Behind Notation (a)

Notation (a) is sometimes used because it follows the grammar rules of C/C . In the declaration char* p;, the asterisk is associated with the variable name p. This implies that *p is of type char.

Case for Notation (b)

However, many programmers prefer Notation (b) for several reasons:

  • It emphasizes the type of the pointer variable. char *p; clearly indicates that p is a pointer to a char variable.
  • It follows the "Rule of Three" in C . In C , the * operator typically denotes a pointer, the & operator denotes a reference, and the [] operator denotes an array. Placing the asterisk next to the type in a pointer declaration aligns with this convention.
  • It enhances readability when declaring multiple pointers simultaneously. For example, char *c, *d; is easier to read than char* c, *d;.

Conclusion

Ultimately, the choice between Notation (a) and Notation (b) is a matter of style and preference. However, C 's emphasis on types makes Notation (b) a more logical and intuitive approach.

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

Statement:
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