Reputation: 1013
I have the following structure
typedef struct _LSHFunctionT
{
double *a;
double b;
} LSHFunctionT, *PLSHFunctionT;
My question is; is there a difference between these two declarations
PLSHFunctionT myPointer1;
and
LSHFunctionT *myPointer2;
and if not, then why do people explicitly use two of them (LSHFunctionT and *PLSHFunctionT). Why not just use LSHFunctionT.
Does it go the same way for the following two declarations
PLSHFunctionT *myPointer3;
and
LSHFunctionT **myPointer3;
Upvotes: 3
Views: 122
Reputation: 97948
The difference is in emphasis. Generally not explicitly writing the * may indicate that the PLSHFunctionT is designed to be used as a handle (without knowing/accessing structure elements ). If * is explicitly written, as in LSHFunctionT *myPointer, it might indicate an array or a structure that is to be used to access the values.
Upvotes: 1
Reputation: 42083
typedef struct _LSHFunctionT
{
double *a;
double b;
} LSHFunctionT, *PLSHFunctionT;
Yes, PLSHFunctionT x;
is equal to LSHFunctionT* x;
And yes, PLSHFunctionT* x;
is equal to LSHFunctionT** x;
The purpose of typedef
is to assign new names to existing types. You can define typedef int lol;
and declare variable lol i;
, but compiler will consider it int
anyway.
You should also check these questions:
When should I use typedef in C++?
Why should structure names have a typedef?
Hope this helps.
Upvotes: 2
Reputation: 96241
There's no difference between the two on the surface. However, with the pointer typedef there's no way to declare it as pointer-to-const, just const-pointer-to-non-const.
For example you can say
const LSHFunctionT* const_ptr;
but const PLSHFunctionT const_ptr2;
makes the pointer const, NOT the pointee.
Finally note that in C++ the whole thing is of questionable legality because names starting with _<capital>
are reserved for the implementation, and that typedefs are almost never used in such a way.
Upvotes: 1
Reputation: 5937
Those declarations are the same. The pointer-typedef approach improves code readability in some cases. One could argue that this:
PLSHFunctionT calls[];
is easier to read than this:
LSHFunctionT *calls[];
Upvotes: 0
Reputation: 361402
Yes. They are exactly same, even in the second case.
I personally prefer using *
explicitly if I want to declare a pointer. It makes the code readable, in most cases. Usage of typedef
of pointer-type reduces readability usually, though sometimes it may increases readability especially when you work with, say, Windows API.
Upvotes: 0
Reputation: 308158
Yes, they are identical.
One good reason to define a pointer type is for complicated expressions. If for example you have a function that takes a reference to a pointer, which do you find easier to understand?
void foo(PLSHFunctionT & ref);
void foo(LSHFunctionT * (&ref));
I'm not even sure I got the syntax correct for the second one!
Upvotes: 2
Reputation: 816
I seem there is no difference. There are different programming styles.
Upvotes: 0