if (p), where p is a pointer - PLEASE READ

rex ballard rb at ccivax.UUCP
Sat Sep 21 09:59:37 AEST 1985


> > An C idiom I see (and write) frequently is
> > 
> > 	if (ptr)
> > 
> > Will this work correctly on a machine where NULL is not 0?  Does it really
> > need to say
> > 
> > 	if (ptr != NULL)
>  
> If you have the K&R book page 97 says:
> 	We write NULL instead of zero however, to indicate that this is
> 	a special value for a pointer.  In general, integers cannot
> 	meaningfully be assigned to pointers; zero is a special case.

NULL should be defined as '0', a good example of why?

-------------------------------
/* file 1 */
struct clx {
    int a;	/* a number >0 */
    char b[2];
};

static struct clx x[10];

newclx(i)
{
	if((i<0)||(i>9))
		return(NULL);
	/* NOSTRICT */	/* turn off lint's type checker */
	return((x[i]=malloc(sizeof(struct clx));
}

getclxa(i)
{
	if((i<0)||(i>9)) return(NULL);
	return(x[i].a)
}
char *getclxb(i)
{
	if((i<0)||(i>9)) return(NULL);
	return(x[i].b)
}
-------------------------------
/* file 2 */

doit()
{
	int a,i;
	char b;
	char *x;
	....
	if(newclx(i))
		return;
	if(getclxa(i),&a)
}
----------------------------

This is a LOUSY example, but was required to illustrate.
Are you going to tell doit(), about the structure of clx?  What about all
the possible name and type clashes?  The object oriented approach is such
that only "file 1" will ever know about clx.  Suppose there were a different
structure in doit() that also used member names 'a' and 'b'? Some compilers
will use the offset of the last structure member (they shouldn't, but they
do!).  The alternative is #include every structure in every module.

In experimenting with object oriented design, I produced a very powerful
report generator that was very flexable and very maintainable (once you
got to the first "primitive").  We just change one module for any report
you like (very much like tbl, with input for binary data).

The most important purpose of the return value is to indicate the
success or failure of the function, anything else can be handled
just as well by using &value. (Make sure someone explains the
use of:
fun(a) **a; {...}

before flaming me about use of return code to return pointers.



More information about the Comp.lang.c mailing list