[Compiler-sig] Error checking macros

Neal Norwitz neal@metaslash.com
Fri, 19 Apr 2002 09:07:43 -0400


I don't know if others have seen the following technique before.  
Eric and I have used it to greatly reduce lines of code for error
checking.  We borrowed this technique from ACE http://www.cs.wustl.edu/~schmidt/ACE.html (I think).

/* START MACRO */

#define ERR_NULL_CHECK(arg, func_name)                                  \
do {                                                                    \
    if (!(arg)) {                                                       \
        PyErr_SetString(PyExc_ValueError,                               \
                        "field " ##arg " required for " func_name);     \
        return NULL;                                                    \
    }                                                                   \
} while (0)

/* END MACRO */

Then code that used to look like this (FunctionDef):

        if (!name) {
                PyErr_SetString(PyExc_ValueError,
                                "field name is required for FunctionDef");
                return NULL;
        }
        if (!args) {
                PyErr_SetString(PyExc_ValueError,
                                "field args is required for FunctionDef");
                return NULL;
        }
        if (!body) {
                PyErr_SetString(PyExc_ValueError,
                                "field body is required for FunctionDef");
                return NULL;
        }

Would become:

	ERR_NULL_CHECK(name, "FunctionDef");
	ERR_NULL_CHECK(args, "FunctionDef");
	ERR_NULL_CHECK(body, "FunctionDef");

Often, the macro has RETURN in the name, to something to indicate
that the macro could return.

Is there any interest in this?

Neal