Info Hiding in C
Steve Summit
scs at adam.mit.edu
Thu Apr 18 15:12:46 AEST 1991
In article <1991Apr17.004044.22940 at ux1.cso.uiuc.edu> unicorn at uxh.cso.uiuc.edu (Harry E Miller) writes:
>I started learning C++ and one of the most interesting things about
>it is information hiding.
>I wish to include optional information hiding within [a] library,
>so that the programer can only get string information from a
>function (not [by using] a macro!).
>I would like any comments (flames if this is just crap) on
>this way of (optionally) hiding the string structure.
>
>Also why won't this work?
>typedef void String[6];
As has been explained, you can't have arrays (or any variables,
struct members, etc.) of type void. If void had a size, it would
be 0, and C is still spooky about 0-sized objects. (void can
only be used as the base for pointer types, as a cast for
"throwing away" a value, and as a placeholder, meaning "no
parameters," in a prototype-form function parameter list.
There's probably another use I forgot.)
As Joe English has explained, using an array of char rather than
an array of void, and using sizeof() to make it the right size,
would probably work for your publicly-visible [Hi, Mark!] struct
placeholder, but it seems marginal (and reminiscent of Dennis
Ritchie's "unwarranted chumminess with the compiler").
Information hiding is fine; I use it myself occasionally.
Assuming that the structure type you wish to "hide" is always
referred to in the calling code via a pointer (the usual case),
you can use a different technique. In the header file, the
entire declaration of the structure's "shape" is #ifdef'fed out
(except for "privileged" modules):
#ifdef BLORT_DEFINE
struct blort
{
int beercooler;
int beckendorf;
int blarneystone;
};
#endif
extern struct blort *blortalloc();
(Obviously, BLORT_DEFINE is #defined only by the source files
implementing the "blort" module, not by users/callers.)
C is perfectly happy dealing with pointers to structures whose
shape isn't known; this technique makes explicit, deliberate use
of that fact. (lint -h says "warning: struct blort never
defined," however. I either use grep -v to eliminate this
message, or turn on BLORT_DEFINE #ifdef lint .)
Another trick I'll use, to "hide" a data type further, is to
provide a typedef:
typedef blort *blortd;
Calling programs then refer to the abstract blortd type ("blort
descriptor"), and don't need to know whether it is a struct
pointer, a small int index into a table somewhere, or something
else.
Steve Summit
scs at adam.mit.edu
More information about the Comp.lang.c
mailing list