I looked through some code and noticed that the convention was to turn pointer types like
SomeStruct*
into
typedef SomeStruct* pSomeStruct;
Is there any merit to this?
No, and it is often used in classes — especially template classes — to define a class-dependent type used throughout the class so that knowledge of the underlying types is not necessary.
The typedef may be used in declaration of a number of pointers of the same type. It does not change the type, it only creates a synonym, i.e., another name for the same type as illustrated below. typedef float* FP; // Now FP represents float* float x,y,z; FP px =&x, py = &y, pz = &z ; // Use of FP.
PLEASE don't typedef structs in C, it needlessly pollutes the global namespace which is typically very polluted already in large C programs. Also, typedef'd structs without a tag name are a major cause of needless imposition of ordering relationships among header files.
typedef is a predefined keyword. You can replace the name of the existing data type with the name which you have provided. This keyword helps in creating a user-defined name for an existing data type. You can also use the typedef keyword with structures, pointers, arrays etc.
Not in my experience. Hiding the '*
' makes the code hard to read.
This can be appropriate when the pointer itself can be regarded as a "black box", that is, a piece of data whose internal representation should be irrelevant to the code.
Essentially, if your code will never dereference the pointer, and you just pass it around API functions (sometimes by reference), then not only does the typedef reduce the number of *
s in your code, but also suggests to the programmer that the pointer shouldn't really be meddled with.
This also makes it easier to change the API in the future if the need arises. For instance, if you change to using an ID rather than a pointer (or vice versa) existing code won't break because the pointer was never supposed to be dereferenced in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With