函数如何返回没有return语句的东西?

时间:2018-03-02 18:02:56

标签: 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

1 个答案:

答案 0 :(得分:3)

这是未定义的行为,标准明确提到

来自§6.9.1¶12C11标准

  

如果到达了终止函数的},并且调用者使用了函数调用的值,则行为未定义。

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

相关问题