"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Where Should the Asterisk Go in C/C++ Pointer Declarations?

Where Should the Asterisk Go in C/C++ Pointer Declarations?

Published on 2024-12-22
Browse:644

Where Should the Asterisk Go in C/C   Pointer Declarations?

Pointers: Declaring with Asterisk Placement

In C and C , pointer declarations vary in style, often causing confusion. The question arises: should the asterisk (*) be placed adjacent to the type name or the variable name?

Placement Conventions

Two primary placement conventions are common:

  • Type-adjacent: The asterisk is placed next to the type name.

    someType* somePtr;
  • Variable-adjacent: The asterisk is placed next to the variable name.

    someType *somePtr;

Significance and Preference

While both conventions lead to the same functionality, the preferred placement depends on personal preference and perceived logicality.

The type-adjacent convention emphasizes the type of the pointer variable, stating "the type of somePtr is a pointer to someType."

Conversely, the variable-adjacent convention emphasizes the type of the pointed-to data, stating "the type of data pointed to by somePtr is someType."

Choice Matters?

The compiler does not distinguish between the two conventions. However, some programmers believe specific placements enhance readability or clarity. Others view it as a matter of style, akin to indentation and brace placement.

Conclusion

Ultimately, the choice between the two placement conventions is subjective. While both are valid and interchangeable, some programmers may find one more logical or aesthetically pleasing than the other. Understanding the underlying semantics and preferences can help inform your coding style and improve communication with other developers.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3