当没有找到匹配的函数时,ac 编译器会做什么

发布于 2024-12-07 01:25:54 字数 347 浏览 6 评论 0原文

考虑以下代码:

#include<stdio.h>
int f()
{
        printf(" hey ");
        return 5;
}
int main()
{
        printf("hello there %d",f(4,5));
        f(4,5);
        return 0;
}

我期望函数“int f()”有太多参数,但即使在严格的 C99 编译中它也会给出输出。为什么会出现这种行为? 但 C++ 编译器似乎给出了错误。

Consider the following code:

#include<stdio.h>
int f()
{
        printf(" hey ");
        return 5;
}
int main()
{
        printf("hello there %d",f(4,5));
        f(4,5);
        return 0;
}

I expected something like too many arguments to function ‘int f()’ but it gives an output even in strict C99 compilation. why is this behavior?
But it seems like a C++ compiler gives an error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

琉璃梦幻 2024-12-14 01:25:54

C 在某些方面比 C++ 严格得多。

C++ 中的函数签名 f() 意味着没有参数的函数,并且符合标准的编译器必须强制执行这一点。相比之下,在 C 中,行为是未指定的,并且编译器不需要诊断是否使用参数调用函数,即使它是在没有参数的情况下定义的。在实践中,现代编译器至少应该警告无效用法。

此外,在 C 语言的函数原型声明(没有定义)中,空括号意味着参数未指定。随后可以使用任意数量的参数来定义它。

为了防止这种情况,请使用以下原型ISO/IEC 9899 6.7.6.3/10

int f(void)

C is much less strict than C++ in some regards.

A function signature f() in C++ means a function without arguments, and a conforming compiler must enforce this. In C, by contrast, the behaviour is unspecified and compilers are not required to diagnose if a function is called with arguments even though it was defined without parameters. In practice, modern compilers should at least warn about the invalid usage.

Furthermore, in function prototype declarations (without definition) in C, empty parentheses mean that the parameters are unspecified. It can subsequently be defined with any number of arguments.

To prevent this, use the following prototypeISO/IEC 9899 6.7.6.3/10:

int f(void)
听风念你 2024-12-14 01:25:54

除了 Konrad 所写的之外,C 还会为您隐式声明函数。例如:

int main(int argc, char** argv)
{
  int* p = malloc(sizeof(int));
  return 0;
}

将在没有包含声明的 #include 的情况下进行编译(可能会出现警告)。

In addition to what Konrad wrote, C will also implicitly declare functions for you. For example:

int main(int argc, char** argv)
{
  int* p = malloc(sizeof(int));
  return 0;
}

will compile (maybe with a warning) without a #include <stdlib.h> that contains the declaration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文