Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!att!ucbvax!bloom-beacon!bloom-picayune.mit.edu!news From: scs@adam.mit.edu (Steve Summit) Newsgroups: comp.lang.c Subject: Re: Info Hiding in C Message-ID: <1991Apr18.051246.5702@athena.mit.edu> Date: 18 Apr 91 05:12:46 GMT References: <1991Apr17.004044.22940@ux1.cso.uiuc.edu> Sender: news@athena.mit.edu (News system) Reply-To: scs@adam.mit.edu Organization: Thermal Technologies, Cambridge, MA Lines: 67 In article <1991Apr17.004044.22940@ux1.cso.uiuc.edu> unicorn@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@adam.mit.edu