As far as I can tell, this is safe. It prints "Should Get Here" and nothing else, as expected and desired. In real life, CantGetHere is a function that actually IS called and does some arithmetic. To avoid a seg fault in line 14, I have a NULL pointer check on line 8. However, I also have one on line 23, so the check on line 8 is redundant, correct? Line 23 will short-circuit if ptr is NULL and hence the CantGetHere() function won't be called, right?

#include <stdio.h>
#include <stdbool.h>


bool CantGetHere(int* ptr)
{
    printf("What the heck?!?  How did I get here?\n");
    if(!ptr)
    {
        printf("Seg fault check.  NULL pointer.\n");
    }
    else
    {
        printf("*ptr equals %d\n", *ptr);
    }
    return false;
}


int main()
{
    int* ptr = NULL;
    if(!ptr || CantGetHere(ptr))
    {
        printf("Should get here.\n");
    }
    else
    {
        printf("Should not get here either.\n");
    }

    getchar(); // pause
    return 0;
}

I'm working off the assumption that the person in this thread is correct and that I understand him correctly.

http://stackoverflow.com/questions/628526/is-short-circuiting-boolean-operators-mandated-in-c-c-and-evaluation-order

Short circuit evaluation, and order of evaluation, is a mandated semantic standard in both C and C++.

If it wasn't, code like this would not be a common idiom

char* pChar = 0;
   // some actions which may or may not set pChar to something
   if ((pChar != 0) && (*pChar != '\0')) {
      // do something useful

   }

That's what I'm going for. A check for a NULL pointer to avoid a seg fault, and then dereferencing the pointer if and only if it's not NULL by use of the || operator. Just want to confirm that ||, like &&, always works from left to right.

Edited 5 Years Ago by VernonDozier: n/a

Line 23 will short-circuit if ptr is NULL and hence the CantGetHere() function won't be called, right?

Correct.

Just want to confirm that ||, like &&, always works from left to right.

Yes. Both are short circuited and have left to right associativity.

Edited 5 Years Ago by Narue: n/a

This question has already been answered. Start a new discussion instead.