c++ - 返回 C++ 中断循环的内部循环?

标签 c++

我正在反转一个双向链表。我的功能是:

Node* Reverse(Node* head)
{
    // Complete this function
    // Do not write the main method. 
    Node* temp = new Node();
    if ( head == NULL) { return head; }
    while ( head != NULL) {
        temp = head->next;
        head->next = head->prev;
        head->prev = temp;
        if (temp == NULL ) { break; }
        head = temp;
    }
    return head;
}

这工作正常。 如果我不使用 break 命令,如果我执行“return head”而不是函数退出 while 循环并出现编译错误:控制到达非 void 函数的末尾 [-Werror=return-type]

Node* Reverse(Node* head)
{
    // Complete this function
    // Do not write the main method. 
    Node* temp = new Node();
    if ( head == NULL) { return head; }
    while ( head != NULL) {
        temp = head->next;
        head->next = head->prev;
        head->prev = temp;
        if (temp == NULL ) { return head; }
        head = temp;
    }
 }

这背后的原因可能是什么?

最佳答案

原因是编译器不知道 temp 总会在某个时刻以 NULL 结束,它只知道循环可以结束,函数将没有返回语句。

正如 CompuChip 所指出的,您可以在末尾添加以下行,以安抚编译器:

throw std::runtime_error("Control should never reach this point");

或者您可以在最后简单地返回 NULL

关于c++ - 返回 C++ 中断循环的内部循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35335645/

相关文章:

c++ - 为什么 INTMAX_MAX 在这里给出错误的结果?

c++ - 在 z3 中设置成员关系

c++ - C++0x 中的新 unicode 字符

c++ - 部分模板特化 : matching on properties of specialized template parameter

c++ - 将套接字绑定(bind)到非临时端口范围内的空闲端口

c++ - 如何在一台机器上构建 vc9 和 vc10 版本的 Boost?

c++ - 将带有引用时间的时间戳转换为格式化时间

c++ - 崩溃后如何处理 "impossible"堆栈跟踪?

c++ - 模板语法帮助

C++ 嵌套类正在生成对外部类的 undefined reference