C语言 无参数行为的 C 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5929711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:36:17  来源:igfitidea点击:

C function with no parameters behavior

c

提问by John Retallack

Can somebody explain to me why the following code does compile without a warning or error?

有人可以向我解释为什么下面的代码编译时没有警告或错误吗?

I would expect the compiler to warn me that the function no_argsdoesn't expect any arguments.

我希望编译器警告我该函数no_args不需要任何参数。

But the code compiles and runs function no_argsrecursively.

但是代码会no_args递归地编译和运行函数。

static void has_args(int a, int b, int c) { 
    printf("has_args\n");
}

static void no_args() {
    printf("no_args\n");
    no_args(1, 2, 3);
}

void main() {
  no_args();
}

回答by Chris Lutz

In C++, void no_args()declares a function that takes no parameters (and returns nothing).

在 C++ 中,void no_args()声明一个不带参数(并且不返回任何内容)的函数。

In C, void no_args()declares a function that takes an unspecified (but not variable) number of parameters (and returns nothing). So all your calls are valid (according to the prototype) in C.

在 C 中,void no_args()声明一个函数,该函数采用未指定(但不是可变)数量的参数(并且不返回任何内容)。所以你的所有调用在 C 中都是有效的(根据原型)。

In C, use void no_args(void)to declare a function that truly takes no parameters (and returns nothing).

在 C 中,用于void no_args(void)声明一个真正不带参数(并且不返回任何内容)的函数。

回答by geekosaur

When you declare a function with an empty argument list, you invoke K&R (pre-prototype) semantics and nothing is assumed about the parameter list; this is so that pre-ANSI C code will still compile. If you want a prototyped function with an empty parameter list, use (void)instead of ().

当你声明一个带有空参数列表的函数时,你调用了 K&R(原型前)语义,并且对参数列表没有任何假设;这是为了使预 ANSI C 代码仍然可以编译。如果您想要一个带有空参数列表的原型函数,请使用(void)代替()