search

Home  >  Q&A  >  body text

关于c++中if(变量)的问题

template <class T>
Node<T>* BinaryTree<T>::getFather(Node<T>* current)
{
    Node<T>* temp = root;
    while(temp != NULL || !traverseStack.isEmpty())
    {
        if(temp)
        {
            if(temp->leftChild == current || temp->rightChild == current)
            {
                return temp;
            }
            if(temp->rightChild)
            {
                traverseStack.pushStack(temp->rightChild);
            }
            temp = temp->leftChild;
        }
        else
        {
            traverseStack.popStack(temp);
        }
    }
    return NULL;
}

而我已经用 if(temp),程序中temp为无法读取,那就不应该进入if语句,为什么程序还是执行if后面的语句了?

ringa_leeringa_lee2803 days ago564

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 13:12:46

    Unable to read is a pointer exception, which does not mean that the pointer is 0

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:12:46

    Your root has not been initialized.
    The value of temp is an address value. As long as the address value is not 0, if will pass.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:12:46

    The amount of information is too small and it is difficult to judge
    Deng Junhui’s data structure? This kind of book has source code. Go to the official website
    NULL now recommends using nullptr

    reply
    0
  • Cancelreply