Pointer Variable Declaration in C/C : Understanding Styles
Declaring pointer variables in C/C has sparked debate over two notations:
(a) char* p;
(b) char *p;
Both styles are valid, but the choice reflects different programming perspectives and emphases.
Style (a): Emphasis on Expressions
This style treats the pointer variable (e.g., p) as a single entity, where the asterisk (*) is part of the name declaration. From a syntax standpoint, the asterisk binds to the name p and indicates the type of the variable (e.g., a pointer to a char). This approach aligns with the traditional C perspective, which emphasizes expressions and considers declarations as a necessary formality.
Style (b): Emphasis on Types
In contrast, style (b) places greater emphasis on types. It considers the asterisk (*) to be a part of the type specification (e.g., a pointer to a char). This style is more in line with the C programming paradigm, which places a strong focus on types and object-oriented principles.
Bjarne Stroustrup's Perspective
Bjarne Stroustrup, the creator of C , advocates for the latter style (int p;) due to its clarity in specifying the type of the variable (int*). He emphasizes that this approach aligns better with the advanced features of C .
Contextual Considerations
When declaring multiple pointer variables in a single line, using the asterisk with the variable name (style (a)) can lead to confusion. For instance:
char c, d;
In this case, it may be less clear that both c and d are pointers to characters. Using the asterisk with the type specification (style (b)) resolves this ambiguity:
char c, d;
Conclusion
The choice between style (a) and style (b) is ultimately a matter of personal preference and programming philosophy. Style (a) may be more intuitive for those coming from a C background, while style (b) is more aligned with the type-centric approach of C .
The above is the detailed content of C/C Pointer Declaration: `char* p` vs. `char *p` – Which Style is Best?. For more information, please follow other related articles on the PHP Chinese website!