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.
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.