c - 函数如何在没有 return 语句的情况下返回一些东西?

标签 c gcc

<分区>

它在 Windows 命令提示符下工作,就像我没有错过 return new_node;

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int value;
    struct Node *next;
 } Node;

Node* create_node(int value) {
    Node *new_node = (Node *) malloc(sizeof(Node));
    if (new_node == NULL) return NULL;
    new_node->value = value;
    new_node->next = NULL;
    // no return statement
}

int main(int argc, char *argv[]) {
    Node *head = NULL;

    // no errors here, head just receives the right pointer
    head = create_node(5);

    return 0;
}

所以函数 create_node(int) 无论如何都会返回指针。它是如何工作的?

使用 gcc 编译(x86_64-posix-seh-rev1,由 MinGW-W64 项目构建)7.2.0

最佳答案

这是未定义的行为,标准清楚地提到了它

来自§6.9.1¶12 C11标准

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

在启用所有警告的情况下编译您的代码。 gcc -Wall -Werror prog.c。在这种情况下,您会看到编译器提到没有 return 语句,尽管它应该返回一些东西。

关于c - 函数如何在没有 return 语句的情况下返回一些东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49074863/

相关文章:

c - 测试混洗代码

c - 赋值操作真的会返回一些东西吗?

c++ - 为什么 GCC 不报告未初始化的变量?

gcc - Yocto 元工具链 fatal error : stdio. h:没有这样的文件或目录

c - 为什么这个程序一次又一次地不显示第一行?

c - 如何跨进程共享ck_list?

c - 在 9 位架构中搜索 8 位对齐的字符串

c - C 中的 Pthread 和信号分配

C: glib.h `pkg-config --cflags --libs glib-2.0` valgrind 仍然可达

c++ - 如何在 clang 中选择特定的 gcc-toolchain?