这个问题在这里已经有了答案:
What does an empty parameter list mean? [duplicate]
(5 个回答)
Accessing the parameters passed to a function with an empty parameter list in C
(2 个回答)
1年前关闭。
我一直在阅读 difference between function()
and function(void)
in C ,我才知道
an empty parameter list in a function declaration indicates that the function takes an unspecified number of parameters
所以 I ran this code :
#include <stdio.h>
void fun();
int main(void)
{
fun(12, 13.22, 1234567890987654321, "wow", 'c');
}
void fun()
{
printf("What happened to those arguments?");
}
我不明白为什么 C 允许这样做。到目前为止,我读过的所有与此相关的帖子都说使用它是不好的做法,它已经过时等。同样从上面的代码中,我认为这些参数的类型也未指定。所以我只想知道“未指定类型的未指定参数”背后的原因:
最佳答案
支持该符号的原因是历史性的。在第一个 C 标准(C89/C90)之前,您不能在 C 中使用原型(prototype);原型(prototype)是标准 C 的最大和最重要的特性之一。因此,所有函数声明都被编写为“空括号”样式(当它们被编写时;大多数返回 int
的函数根本没有声明)。 void
类型也被添加到 C89/C90 中,尽管一些编译器在标准最终确定之前支持它。
因为对于 C89/C90 的成功至关重要的是现有代码大部分应该继续工作,所以标准必须允许空括号样式。因此,您的代码可能是用准标准 C 编写的:
#include <stdio.h>
int fun(); /* This declaration would probably have been absent */
int main(void)
{
fun(12, 13.22, 1234567, "wow", 'c');
return 0; /* This was required until C99 to give reliable exit status */
}
fun(i, d, l, s, c) /* No return type - implicitly returns int */
long l; /* Defined out of sequence - bad style, but legal */
char c; /* Passed as int; converted to char in function */
char *s; /* Should define all pointer arguments */
double d; /* No definition of i; it was an int by default */
{
printf("This is what happened to those arguments:\n");
printf("i = %d\n", i);
printf("d = %f\n", d);
printf("l = %ld\n", l);
printf("s = [%s]\n", s);
printf("c = %c\n", c);
/* No return statement - don't use the value from the function */
}
出于好奇:您可以在函数定义中省略
char *s;
行,它仍然编译并产生相同的输出。不过,尝试这样做是个坏主意。您可以将 int fun();
行替换为 static fun();
,并且在不请求诊断时代码可以干净地编译。即使您现在使用 GCC 9.3.0 编译此文件 (
old31.c
),您也不会收到任何警告:$ gcc -std=c90 -o old31 old31.c
$
您所写的示例绕过了向后兼容性规定。使用
void
意味着它是新代码(它在许多准标准 C 编译器中无效,因为它使用了 void
)。并且新代码不应无故利用向后兼容条款。在 1991 年和当前的千禧年都是如此(但在 1991 年,有更多充分的理由来利用向后兼容条款)。良好的准标准代码通常按使用顺序列出所有参数。省略的定义和乱序的定义并不完全令人满意。您询问:
- What can be done with those arguments?
在问题的代码中,无法对参数进行任何操作。调用者将值压入堆栈,并在函数返回时将它们弹出。被调用的函数不知道它们的存在并且不能对它们做任何事情。
- Is it possible to access those arguments within the function?
不——不使用任何标准机制。
关于c - function() 中未指定的参数会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62010502/