c - 在函数参数中使用 'void'

标签 c

<分区>

Possible Duplicate:
C void arguments

我刚开始使用 C,我找不到这个问题的答案...

有什么区别吗

int foo() { }

int foo(void) { }

我应该选择哪个,为什么?

请注意,此问题也适用于:int main。当我不需要任何命令行参数时,它应该是:int main 还是 int main(void)

最佳答案

根据标准(参见 C99 第 5.1.2.2.2 节“程序启动”),main 的两种规范形式是:

int main (void);
int main (int argc, char *argv[]); // or equivalent such as char **argv

其他是特别允许的,但那些是必需的。

关于 fn(void)fn() 之间的首选形式,我更喜欢前者,因为我喜欢明确声明没有参数。

还有一个细微的差别。 C99 第 6.7.5.3 节“函数声明符”第 10 段指出:

The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters.

同一部分的第 14 段显示了唯一的区别:

An identifier list declares only the identifiers of the parameters of the function. An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters. The empty list in a function declarator that is not part of a definition of that function specifies that no information about the number or types of the parameters is supplied.

换句话说,它与函数定义中的 void 意思相同,但不是在独立声明符(即原型(prototype))中的意思。 int fn(); 表示参数信息未知,int fn(void); 表示没有参数。

这意味着:

int fn();
int fn (int x) { return x; }
int main (void) { return fn(0); }

有效但是:

int fn(void);
int fn (int x) { return x; }
int main (void) { return fn(0); }

不是。

关于c - 在函数参数中使用 'void',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5075530/

相关文章:

c - C 中解引用和引用指针的流程

Python:Ctypes如何检查内存管理

c - 从文件中读取数字并将其存储在 C 中的二维数组中

c - 垃圾值如何分配给c中的变量

c - TicTacToe 打印获胜者

java - C 等同于 Java 中的 Arrays.sort - qsort? (我如何找到其实现的性质)

c - 如何用C语言使用VTK?

C 读取函数读取比请求更多的字节

c - 使用 memcmp() 时出现段错误

java - 什么会导致 Java native 函数(在 C 中)在进入时出现段错误?