akmal
akmal

Reputation: 665

Is there good argument checking strategy?

instead of checking every input pointer argument with if condition if( in != NULL ), is there better way to do this. One method is to create some macros, like

#define CHECK_ARG(x) if(!(x)) { return 0; }

In code it's look like this

int some_func( int * first_arg, int * second_arg )
{
    CHECK_ARG( first_arg );
    CHECK_ARG( second_arg );

    // some operations
    //
}

In my opinion this is good approach, but before adding this, I want to know is there any better ways doing this?

Thanks in advance!

Upvotes: 2

Views: 1103

Answers (4)

Diomidis Spinellis
Diomidis Spinellis

Reputation: 19385

In your function write

assert_or_return(first_arg != NULL);
assert_or_return(second_arg != NULL);

Define assert_or_return so that in the debug version it will fire up the debugger (by calling abort), and in the release version it will log the error and return (as you want to do). I assume you're confident that returning from the function when one of the arguments is NULL will do more good than harm in the production version of your application. If by returning early you will irrevocably corrupt your users' data or cause a furnace to explode, it would be better to terminate early, perhaps with a custom error message.

The following example illustrates how your idea can be implemented.

#ifdef NDEBUG
#define assert_or_return(expr) do { \
  if (!(expr)) { \
    fprintf(logfile, "Assertion %s in %s(%d) failed\n", #expr, __FILE__, __LINE__); \
    return 0; \
  } \
} while(0)
#else
#define assert_or_return(expr) do { \
  if (!(expr)) { \
    fprintf(stderr, "Assertion %s in %s(%d) failed\n", #expr, __FILE__, __LINE__); \
    abort(); \
  } \
} while(0)
#endif

Upvotes: 1

Reto Aebersold
Reto Aebersold

Reputation: 16644

Maybe you can assertions. Have a look at assert.h.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272822

Macros are usually frowned upon, but sometimes extermely useful. But macros that have "hidden" side effects (like returning) are potentially dangerous, because they're difficult to spot. At least consider renaming your macro to make this explicit, e.g. CHECK_ARG_AND_RETURN_IF_INVALID. It's verbose, but it's hard to miss.

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 191058

I would use some ASSERT in there instead - at least in your debug version.

Also, what George said - its not readable and clear that it returns 0.

Upvotes: 6

Related Questions