函数如何返回没有return语句的东西? [重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

它在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

c gcc
1个回答
3
投票

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

来自§6.9.1¶12C11标准

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

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

© www.soinside.com 2019 - 2024. All rights reserved.