为什么 int 函数即使没有在 C 中首先声明也能工作

Why int function works even when they're not declared first in C

我知道,为了使用函数,您必须在主函数之上定义它,或者至少先声明它。但是我注意到,如果我的函数具有 intvoid return type[=11=,C 不会抛出错误消息]

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

int main()
{
    printf("Answer: %d", cube(3));
    return 0;
}

int cube(int num)
{
    return num * num * num;
}

我对 C 还是个新手,你能解释一下为什么该规则不影响 int return 类型

几十年前,函数类型默认返回 int。 1990 C 标准在第 6.3.2.2 条中说:

… If the expression that precedes the parenthesized argument list in a function call consists solely of an identifier, and if no declaration is visible for this identifier, the identifier is implicitly declared as if, in the innermost block containing the function call, the declaration

extern int <em>identifier</em>();

appeared…

一些 C 编译器仍然对此进行了规定,这在这个千年中具有可疑的价值。您应该要求编译器应用更现代的标准,例如通过使用 Clang 开关 -std=c17,以及使用 -Wmost-Wall 启用警告,除非您有机会编译代码已经超过三分之一个世纪了。