I've been reading around SO and have come across the following questions which touch on why typedefing pointer types is bad.
Opaque C structs: how should they be declared? and Const-correctness and immutable allocated objects
I was wondering if someone could expand and explain why typedefing pointer types is bad and perhaps provide some examples of where errors might occur.
Also, if typedefing pointer types is indeed a no-no, then why does the Win32 API do it? in Win32 HANDLE
(and effectively Handle types) are typedef'd as a void *
.
Johannes has already remarked that typedef
'ing pointers is not inherently bad, and I agree.
Some guidelines, based on my subjective opinion of clarity & maintainability:
Generally do typedef
function pointer types.
Reason:
Function pointer declarations can get really messy & unreadable.
Generally don't typedef
raw object pointers where the pointer type is not an abstraction (e.g., when you just need a "pointer to T").
Reason 1:
It's more clear to see Foo*
or Foo const*
than, say, FooPtr
. With the name you have to look up the name to see what it's defined as. Perhaps it's some smart pointer, perhaps it's a pointer to const
, whatever; the name makes you needlessly look elsewhere.
Reason 2:
Some programmers are confused by the combination of const
and typedef
'ed pointer types. E.g. in Microsoft code I've seen the equivalent of FooPtr const
many times, where the programmer evidently thought it meant Foo const*
. But it doesn't, it means Foo* const
.
Generally do typedef
also a raw object pointer when the pointer type is an abstraction, a pointer type that conceivably can be replaced with some other type in the future, like e.g. HANDLE
.
Reason: The same as for using named constants: without a proper name a search and replace can change occurrences that mean something else, and can fail to change occurrences that are not expressed in the exact "right" way.
However, as with nearly all kinds of style, the arguments pro and con are pretty weak, and so the choice in the end boils down to personal preference, coding standards, co-workers' opinions, and so on.
Given a free choice the above is generally what I'd choose. But I have deviated from those guidelines/rules in special cases. As with good art, good code is produced by those who know the rules well enough to also know when to break 'em…
Cheers & hth.,
It's not objectively bad to typedef pointer types. Much well written code uses it to typedef pointer to handler function types and it's also common for things like HANDLER
.
It may be one's personal opinion that it's bad, but it definitely isn't well-accepted opinion. I for one don't agree with that opinion at all. I myself use that option more seldom, but I still don't think it's "bad".
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