为什么 gcc 允许将参数传递给定义为没有参数的函数? [英] Why does gcc allow arguments to be passed to a function defined to be with no arguments?

查看:20
本文介绍了为什么 gcc 允许将参数传递给定义为没有参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么这段代码会编译?

I don't get why does this code compile?

#include <stdio.h>
void foo() {
    printf("Hello
");
}

int main() {
    const char *str = "bar";
    foo(str);
    return 0;
}

gcc 甚至没有警告我向 foo() 传递了太多参数.这是预期的行为吗?

gcc doesn't even throw a warning that I am passing too many arguments to foo(). Is this expected behavior?

推荐答案

在 C 中,使用空参数列表声明的函数在被调用时接受任意数量的参数,这些参数受到通常的算术提升.调用者有责任确保提供的参数适合函数的定义.

In C, a function declared with an empty parameter list accepts an arbitrary number of arguments when being called, which are subject to the usual arithmetic promotions. It is the responsibility of the caller to ensure that the arguments supplied are appropriate for the definition of the function.

要声明一个带零参数的函数,你需要写void foo(void);.

To declare a function taking zero arguments, you need to write void foo(void);.

这是历史原因;最初,C 函数没有原型,因为 C 是从 B 演变而来的,无类型语言.添加原型时,为了向后兼容,原始的无类型声明保留在语言中.

This is for historic reasons; originally, C functions didn't have prototypes, as C evolved from B, a typeless language. When prototypes were added, the original typeless declarations were left in the language for backwards compatibility.

要让 gcc 对空参数列表发出警告,请使用 -Wstrict-prototypes:

To get gcc to warn about empty parameter lists, use -Wstrict-prototypes:

在未指定参数类型的情况下声明或定义函数时发出警告.(如果前面有指定参数类型的声明,则允许旧式函数定义而不会发出警告.)

Warn if a function is declared or defined without specifying the argument types. (An old-style function definition is permitted without a warning if preceded by a declaration which specifies the argument types.)

这篇关于为什么 gcc 允许将参数传递给定义为没有参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆