在C中使用"void"

Nat*_*ate 11 c

我很困惑为什么我们需要传递void给C函数:

int f(void) { return 0; }
Run Code Online (Sandbox Code Playgroud)

int f() { return 0; }
Run Code Online (Sandbox Code Playgroud)

什么是正确的做法,为什么?

Kei*_*son 16

在C中,int f()是一种旧式的宣言.它表示f期望一个固定但未指定的数字和类型的参数.例如,给定int f() { return 0; },编译器不会抱怨f(42),或者f("hello, world")(虽然这种调用的行为是未定义的).

int f(void)显然说f没有参数.

(C++有不同的规则; Stroustrup并不关心与旧C代码的向后兼容性.)


Foo*_*Bah 5

这是C的遗迹.

f(void)不带参数,所以f(1)无效.

f()表示参数未指定,因此f(1)在此处有效.