search

Home  >  Q&A  >  body text

c++ - 关于C语言链表的while循环

while(num!=q->num&&q!=NULL){
q=q->next;
}//q为一个链表

这样写有什么问题吗?经过我不断的debug,基本把错误缩小到这句上,程序也能运行,但是输入一个数赋值给num后,程序会报错。具体表现为程序停止工作。

已找到原因,吧q!=NULL和num!=q->num调一下位置就行了。

伊谢尔伦伊谢尔伦2773 days ago456

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:43:38

    && operator first evaluates the expression on the left. If it is false, it returns false directly. If it is true, it evaluates the expression on the right.

    reply
    0
  • PHPz

    PHPz2017-04-17 14:43:38

    Isn’t this a problem of short-circuit evaluation?

    As operand expressions of "&&" and "||" operators, when these expressions are evaluated, as long as the final result can be determined to be true or false, the evaluation process will terminate. , this is called short-circuit evaluation. This is an important property of these two operators.

    You should first determine whether q is null. According to the rules of short-circuit evaluation, the statement num!=q->num will be executed only when q is not null. In this way, the problem of null pointer can be avoided.

    reply
    0
  • Cancelreply