[comp.lang.c] hidden structure decls

dandb@k.gp.cs.cmu.edu (Dean Rubine) (12/08/88)

    I'm sorry if this has been discussed here before, but I decided to stop
reading this bboard a few years ago in order to get some work done (.5 :-). 
Recently (I've been procrastinating) I started reading c.l.c again, and
realized it would be a good place to ask what people thought about using
typedefs to hidden structures so that a file which uses a type would not be
allowed to access the representation of the type directly (i.e. the standard
motherhood abstract data type/information hiding idea).  Here's an example,
probably too long and not very interesting or illustrative:  

/*-------- File list.h --------*/

/* list of integers */

typedef struct list *List;

#define	nil 	((List) 0)

List	cons(int, List);
int	car(List);
List	cdr(List);

/*-------- File list.c --------*/

#include "list.h"
#include <stdio.h>

struct list { 
	int	first;
	List	rest;
};

List
cons(int first, List rest)
{
	char *malloc();
	register List l = (List) malloc(sizeof(struct list));
	if(l == NULL) fprintf(stderr, "cons: no mem\n"), exit(1);
	l->first = first;
	l->rest = rest;
	return l;
}

int
car(register List l)
{
	if(l == nil) fprintf(stderr, "car of nil\n"), exit(1);
	return l->first;
}

List
cdr(register List l)
{
	return l == nil ? nil : l->rest;
}

/*-------- File app.c --------*/

#include "list.h"
#include <stdio.h>

main()
{
	List l, l1 = cons(3, cons(2, cons(1, nil)));
	for(l = l1; l != nil; l = cdr(l))
		printf("%d ", car(l));
	printf("\n");
}

/*-----------------------------*/

The only point of all this is that app.c (and any other file that includes
list.h) is able to use lists through the supplied functions, but not able
to peek at the representation.  

   Comments?  If this has been discussed before (or even if not) feel free
to mail me replies and I'll summarize if anyone's interested.

-- 
ARPA:       Dean.Rubine@CS.CMU.EDU	UUCP: ...!seismo!k.gp.cs.cmu.edu!dandb
PHONE:	    412-268-2613		[ Free if you call from work]
US MAIL:    Computer Science Dept / Carnegie Mellon U / Pittsburgh PA 15213
DISCLAIMER: My employer wishes I would stop posting and do some work.
--