Declaring Pointers: Left or Right Asterisk Placement
In C and C , pointers can be declared in two distinct ways: with the asterisk adjacent to the type name or adjacent to the variable name. This variance has sparked a debate among developers regarding its significance and preferred approach.
Left Asterisk Placement: someType* somePtr
This style emphasizes the type of the pointer variable. It conveys that "the type of somePtr is a pointer to someType." This approach aligns with the concept that in C , the * operator denotes the indirection of a pointer, aligning with the placement next to the type.
Right Asterisk Placement: someType *somePtr
This style highlights the type of data pointed to by the pointer. It suggests that "the type of data pointed to by somePtr is someType." The asterisk is adjacent to the variable name, and because a pointer is a variable that contains an address, this placement underscores that the variable stores a memory address that references data of a certain type.
Style Preference
The choice between left and right asterisk placement is ultimately a matter of personal preference. Some developers favor the "C " style due to its focus on the type of the pointer itself, while others opt for the "C" style to emphasize the type of the data the pointer points to. Ultimately, both declarations have the same semantic meaning and are interpreted identically by the compiler.
Middleware Placement
In an attempt to reconcile the two approaches, some developers place the asterisk in the middle: someType * somePtr. This compromise avoids committing to either the type of the pointer variable or the type of the pointed-to data, aiming to appease both perspectives.
In conclusion, the choice between left or right asterisk placement when declaring pointers is driven by personal preference and mental models. Both approaches are valid and convey the same information, allowing developers to choose the style that best aligns with their understanding and coding style.
The above is the detailed content of Left or Right Asterisk in C Pointer Declarations: What's the Difference and Which is Better?. For more information, please follow other related articles on the PHP Chinese website!