Checking non-NULL vs NULL


Given this snippet from the book:

        // is rPtr non-NULL?
        if (rPtr) {
            *rPtr = sqrt(x * x + y * y);
        // is thetaPtr NULL?
        if (!thetaPtr) {

Would it also be valid to check if thetaPtr was non-NULL, and then encapsulate the whole theta calculation in that ‘if’ block? That way, if thetaPtr was NULL, the if block would be skipped (and the function would return by virtue of having no further code to execute), and if thetaPtr was non-NULL, the theta calculation would proceed.

I guess I’m just curious if you used the opposite check to illustrate the variety of ways to check for NULL vs not-NULL, or if there is an explicit logical reason it has to be the way it is in the book that I am missing?

(I get why you can’t check if rPtr is NULL and simply return, because then the function would never get a chance to do the theta calculation in the event of a NULL rPtr but a valid thetaPtr, which would be a bug.)


Hmm. I think I understand the question, and I think the answer is “Yes, you could check for the opposite and wrap the last half of the function in an if-statement.”

But, if you want to be sure, why don’t you post your solution here, and I’ll check it.


I am just curious of wether I understood this. Would it be possible to get the same check if I write the code like this:

    // Is thetaPtr non-NULL
    if (thetaPtr) {
        // Calculate theta   
        float theta;
        if (x == 0.0) {
            if (y == 0.0) {
                theta = 0.0; // technically considered undefined
            } else if (y > 0 ) {
                theta = M_PI_2;
            } else {
                theta = - M_PI_2;
        } else {
            theta = atan(y/x);
        // Store theta in the supplied address
        *thetaPtr = theta;
    else {

Would the code then be faster executed in average if it is used several times and thetaPtr is NULL occours only very rarely?



That looks like it would work. You don’t have to have the else { return; } on the end in this particular case, since the function ends after the if statement and will be returning anyway. But it won’t cause a problem if you leave it in.

I suppose it would be just slightly faster than the original version if the pointer is normally non-NULL. You could make a similar optimization for the (x == 0.0) check on the assumption that x being exactly 0.0 would also be a rare occurrence.