tags:

views:

106

answers:

5

I am coming across situations such as this:

if(x == NULL)
{
  printf(" The value of X is Null, exiting..");
  return -1;
}

and this "situation" gets repeated many , many times..... laziness aside is there a better way to write this ?

Cheers!

+3  A: 

Going on your comment to @sbi, yes you can do this with a macro.

#define RETURN_MINUS_ONE_IF_NULL(x) \
do \
{\
    if (x == NULL) \
    { \
        printf(#x " is null, exiting\n"); \
        return -1; \
    } \
} \
while (0)

Then you would call this as

signed int foo (int *x)
{ 
    RETURN_MINUS_ONE_IF_NULL(x);

    /* ... */
}

HOWEVER, I would strongly advise against doing this - hiding a return from a function within a macro is very confusing to a casual reader.

Vicky
Thanks! Unfortunately i can't go via assert route and this as you mentioned... looks too messy :)
Ricko M
+1  A: 

There's no reason why a macro cannot be used, although it should be more general than checking for NULL pointers.

For instance,

#define FAIL(condition, msg) if ((condition)) { fprintf(stderr, (msg)); exit(1); }

Then you have,

FAIL(x == NULL, "could not instantiate x");

Eric Brunstad
+1  A: 

In the case where this situation is not meant to happen at all, you are searching for the concept of assertions.

Consider the C "assert(int expr)" function. When "expr" is equals to 0 (expr is false, in a boolean world), the program will exit and will (generally) print the location where the assertion failed.

Noe
A: 

If you can support exiting the process when the pointer is null, you should use the assert function:

void assert(int expression);

Otherwise, the macro is the only way to handle this unfortunately.

Benoit Thiery
`assert` is a macro too, by the way.
Steve Jessop
A: 

The better way to write this is as a doxygen comment or an entry in whatever documentation system you use, informing callers of something that they should already know: NULL is not a valid pointer. Even there, rather than special-casing the remark that NULL is not valid, it makes more sense to simply document the argument x as being a valid pointer to type foo. This covers the billions of other invalid pointer values as well. Personally I prefer not to waste time documenting this requirement for every function but instead document as a general part of my library interfaces that, unless otherwise specified for a particular function, all pointer arguments must be valid pointers to objects of the corresponding type.

If you really do want to document this at the source level too, C99 has a way, using:

void foo(int x[static 1]);

instead of one of the following:

void foo(int *x);
void foo(int x[]);
R..