Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to typedef pointers?

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?

like image 898
Unknown Avatar asked Apr 15 '09 03:04

Unknown


People also ask

Is typedef a good practice?

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.

What is a typedef pointer?

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.

Should I typedef structs in C?

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.

What is the purpose of typedef how typedef is useful in structure?

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.


2 Answers

Not in my experience. Hiding the '*' makes the code hard to read.

like image 36
sigjuice Avatar answered Sep 22 '22 10:09

sigjuice


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.

like image 193
Artelius Avatar answered Sep 22 '22 10:09

Artelius