I have an if/else if statement that looks like this:
if(myNode->left->is_red){
//CODE TO EXECUTE
}
else if(myNode->right->is_red){
//CODE TO EXECUTE
}
The conditions I am checking are whether certain data fields in each node are set. BUT, the problem is, if I access a NULL pointer and try to access its members (which don’t exist), then I run into a segmentation fault issue. But if I do an if statement before the if, and again before the else if, to check whether or not the node is NULL, then I lose the ability to use an if/else if statement.
Is there any way I can achieve a solution to both problems?
I’m assuming the issue is that
leftand/orrightis NULL, hence your segfault?If so, then use AND.
e.g:
This uses short-circuit evaluation: although the
myNode->left->is_redandmyNode->right->is_redare still in theifconditions, ifmyNode->leftisNULL(ormyNode->rightrespectively), they wont be evaluated and you will not have your segfault.