Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return NULL or nothing from function

Tags:

c

I have some functions where I would like to return NULL on failure, and on success they do not need to return anything. I have been using void * function_name(...), but it still requires me to return something.

The reason I am doing this is to detect failure as part of a python C extension and they recommend that the innermost function set any exception, return NULL and then do that up through the stack.

What is the best practice in this situation? Return 0, -1 or something similar?

like image 415
Christian P. Avatar asked Jun 29 '26 22:06

Christian P.


1 Answers

In pure C terms, the easiest is to return a Boolean flag indicating success/failure.

As far as integration with Python is concerned, another approach is:

PyObject* func() {
    ...
    if (error) {
        /* set the exception */
        PyErr_Format(PyExc_..., ...); /* TODO: fill in as appropriate */
        return NULL;
    }
    /* return None */
    Py_RETURN_NONE;
}
like image 79
NPE Avatar answered Jul 02 '26 13:07

NPE