Structure Pointer Dereferencing
Author Message
Structure Pointer Dereferencing

Dear All,

Is it a good practice to *strictly* avoid dereferencing of structure

I recently came across this neat trick to do the same.

To access the fields of structures, I use the following macros:

#define V(a)    ((void)0,(a))
typedef struct foo_1 foo_1;

struct foo_1
{
type_1          f_1 ;  // fields
type_2          f_2;
.
.

Quote:
};

#define dereferencer_1(a)       (a)

// following macro used to set fields
#define x_f_1_foo_1(a)          (dereferencer_1(a)->f_1)
.....
.....
.....
#define x_f_n_foo_1(a)          (dereferencer_1(a)->f_n)

#define f_1_foo_1(a)            V(x_f_1_foo_1(a))
.......
......
#define f_n_foo_1(a)            V(x_f_n_foo_1(a))

Can any one point out the flaws in this approach? Any
ideas/alternatives to do the same?

Regards,
Rohit
--

Fri, 18 Feb 2005 11:40:43 GMT
Structure Pointer Dereferencing

Quote:

> Is it a good practice to *strictly* avoid dereferencing of structure
> pointers inside your code ?

No.  Who gave you that idea?  There is nothing wrong with
dereferencing structure pointers.

Quote:
> I recently came across this neat trick to do the same.

> To access the fields of structures, I use the following macros:

> #define V(a)       ((void)0,(a))

I suppose you're using this to transform an lvalue into an
rvalue?  You might have noted so, because otherwise it's a
useless no-op.

Quote:
> #define dereferencer_1(a)  (a)

This macro, however, seems truly pointless.

Quote:
> // following macro used to set fields
> #define x_f_1_foo_1(a)             (dereferencer_1(a)->f_1)

So this is an lvalue that can be used to modify a member.

Quote:
> // to read a field
> #define f_1_foo_1(a)               V(x_f_1_foo_1(a))

And this is an rvalue that cannot.  Very clever.

Quote:
> Can any one point out the flaws in this approach? Any
> ideas/alternatives to do the same?

The main flaw is that in general the complication isn't worth
it.  A secondary flaw is that the names are unreadable.
--
"It would be a much better example of undefined behavior
if the behavior were undefined."
--Michael Rubenstein
--

Sun, 20 Feb 2005 23:47:50 GMT
Structure Pointer Dereferencing

Quote:

> Can any one point out the flaws in this approach?

Yes, it seems completely insane.
--

Sun, 20 Feb 2005 23:47:55 GMT
Structure Pointer Dereferencing
The only thing you need to avoid when using struct pointers
is making assumptions about their alignment in memory.
Otherwise use
myStruct.item
or
ptr2mystruct->item
--

Sun, 20 Feb 2005 23:48:34 GMT

 Page 1 of 1 [ 4 post ]

Relevant Pages