C 函数定义中可以省略 void 参数吗?

问题描述 投票:0回答:1

我知道在现代 C 中,当我们声明一个没有参数的函数时,我们必须指定 void 关键字,例如:


int fx(void);

但是对于函数定义我有一些疑问。例如,这两个定义是否相同?


int fx(){} /* it is as if it was void */

int fx(void){}

我猜这两个定义是相同的,因为我看到很多代码在参数中省略了 void 关键字....

c function parameters void iso
1个回答
0
投票

如果参数是

void
,如果使用某个参数调用该函数,编译器将能够检测到错误:

int fx(void);

int main(int argc, char **argv) {
    fx(1); // -> will produce an error at compile time
    return 0;
}

另一方面,如果声明中没有参数,编译器将不会检查函数调用时的参数:

int fx();

int main(int argc, char **argv) {
    fx(1, 2); // -> no error here
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.