Hi
why we cannot have static as a structure member?
In part because the answer to your second question is "no". Without
"restricted access", a static structure member is just a global variable
with a name related to the structure type. You can get the same effect
by writing:
int struct_xxxx_i = 42;
(and you can get some data hiding if you make it static.)
& also is there any way to achive data hiding in C at this level( i.e.
access only selected structure member ) following code gives syntax
error
struct xxxx
{
static int i; //
int j;
};
There is no direct language support for hiding structure members in C, but
you can do a lot of data hiding like this:
In widget.h:
struct widget {
/* "public" members of widgets here */
};
/* interface to widgets: */
struct widget *make_widget(/* args */);
void fiddle_widget(struct widget *wp /* other args */);
In widget.c:
#include "widget.h"
struct real_widget {
struct widget public;
/* "private" members here */
};
static int widget_count = 0;
struct widget *make_widget(/* args */)
{
struct real_widget *rwp = malloc(sizeof *rwp);
if (rwp) {
++widget_count;
/* other code */
return &rwp->public; /* or: return (struct widget *)rwp; */
}
else return NULL;
}
void fiddle_widget(struct widget *wp /*other args */)
{
struct real_widget *rwp = (struct real_widget *)wp;
/* whatever ... */
}
Many C programmers would find this rather over the top: just put all the
(non static) structure members in one structure and tell people in a
comment what they can and cannot touch.
On the other hand, putting static data in a file like this is often done in
C programs.
Of course, if all the data is "private" then you can just have one
structure and move its definition into widget.c. Outside of that file you
pass around struct widget pointers with no idea what they have in them --
the type becomes "opaque".