Mailinglist Archive: opensuse-programming (118 mails)

< Previous Next >
Re: Re: [suse-programming-e] Programming standards!
  • From: <synthetoonz@xxxxxxxxxxxxx>
  • Date: Thu, 21 Apr 2005 13:37:09 -0400
  • Message-id: <20050421173709.HVQP2072.imf22aec.mail.bellsouth.net@xxxxxxxxxxxxxxxxxx>

> From: Colin Carter <colincarter@xxxxxxxxxxxxxx>
> On Thursday 21 April 2005 22:31, Randall R Schulz wrote:
> > On Thursday 21 April 2005 02:48, Michael Stevens wrote:

> > > In C++ it would seem that the 'const void * NULL = 0' definition
> > > would be a good thing as opposed to the literal '0' which Bjarne is
> > > recommending.
> >
> > I used these routinely in my C++ work:
> >
> > const void *NIL = 0;
> > const char NUL = 0;
> >
> > I would use a naked 0 in source code only where the context was actually
> > integer, not pointer or character, in which case I'd use on of these.

> I like this idea - it makes it clear about what you mean, whereas (to me
> anyway) there is always confusion with NULL which is not even NUL.
>
> How do you write that a pointer ptr is pointing nowhere?
> That is, the value of the pointer is zero. I mean so that it is clear
> that it is not pointing to a zero value.
> Pardon my ignorance, but my preference is for FORTRAN and we are
> positively discouraged from using pointers because all of our variables
> are in fact addresses (pointers) and not 'values' as in C.

If you want to know if a pointer is NULL, that is, not a valid pointer, you just compare the pointer. If you dereference the pointer (that's the * ) then you are examining what the pointer is pointing at.

Explicitly stated, if (pointer == NULL) /* The pointer must be NULL */

The joy of ! (that's NOT) is that it helps do the same sort of check with less typing.

So, you could say if ( !pointer ) and it means the same thing as above.

! can save you from that dreaded = vs == typo where you inadvertently write code that assigns a value instead of compares.


A random function that protects itself from being passed a 0 (that's NULL pointer)...

char * foo(int x, char * bar)
{
if ( !bar ) /* pointer must be zero */
return NULL;

/* .... blah blah .... */

return somethingnotzero;
}


elsewhere some code calls foo()...

...
char * mybar = NULL;

/*Maybe mybar is assigned something later, or maybe not */

if (!foo(2, mybar) )
{
/* foo returned NULL, so it is an error */
/* do something about the error */
}
else
{
/* I like success. foo worked. */
}



Very common in code is something that checks if the pointer is (not) NULL and that what it points to is also (not) NULL (or zero) . i.e. you want to know that a string pointer is valid and that it points to a string with at least one real character in it....

char * p = NULL;

/*.... maybe we made p point to a string or not.... */

if ( !p || !*p )
printf ("There is no P!\n");



< Previous Next >