为什么海湾合作委员会允许参数传递给定义为不带参数的函数吗? [英] Why does gcc allow arguments to be passed to a function defined to be with no arguments?

查看:140
本文介绍了为什么海湾合作委员会允许参数传递给定义为不带参数的函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么这是否code编译?

I don't get why does this code compile?

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

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.

要声明一个函数取零的参数,你需要写无效美孚(无效);

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

这是历史原因;最初,C函数没有原型,为C从,无类型语言的进化。当添加的原型,原来的无类型声明留在向后兼容的语言。

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警告有关参数列表为空,则使用<一个href=\"http://gcc.gnu.org/onlinedocs/gcc-4.4.0/gcc/Warning-Options.html\"><$c$c>-Wstrict-prototypes:

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

警告如果一个函数或声明没有指定参数类型定义。 (一旧式函数定义是不容许如果一项宣言,指定函数参数类型pceded $ P $警告。)

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.)

这篇关于为什么海湾合作委员会允许参数传递给定义为不带参数的函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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