C ++或C中foo(void)和foo()之间有区别吗?

C ++或C中foo(void)和foo()之间有区别吗?

Is there a difference between foo(void) and foo() in C++ or C?

考虑这两个函数定义:

1
2
3
void foo() { }

void foo(void) { }

这两者有什么区别吗? 如果没有,那为什么void参数呢? 美学原因?


在C:

  • void foo()表示"函数foo采用未指定数量的未指定类型的参数"
  • void foo(void)表示"函数foo不带参数"

在C ++中:

  • void foo()表示"函数foo不带参数"
  • void foo(void)表示"函数foo不带参数"

因此,通过编写foo(void),我们在两种语言中实现相同的解释,并使我们的标题多语言(尽管我们通常需要对标题做更多的事情,使它们真正成为跨语言;即,将它们包装在如果我们正在编译C ++)。


我意识到你的问题与C ++有关,但是当谈到C时,答案可以在K&R,第72-73页找到:

Furthermore, if a function declaration does not include arguments, as
in

1
double atof();

that too is taken to mean that nothing is to be assumed about the
arguments of atof; all parameter checking is turned off. This special
meaning of the empty argument list is intended to permit older C
programs to compile with new compilers. But it's a bad idea to use it
with new programs. If the function takes arguments, declare them; if
it takes no arguments, use void.


C ++ 11 N3337标准草案

没有区别。

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf

附件C"兼容性"C.1.7第8条:申报人说:

8.3.5 Change: In C ++ , a function declared with an empty parameter list takes no arguments. In C, an empty
parameter list means that the number and type of the function arguments are unknown.

Example:

1
2
3
int f();
// means int f(void) in C ++
// int f( unknown ) in C

Rationale: This is to avoid erroneous function calls (i.e., function calls with the wrong number or type of
arguments).

Effect on original feature: Change to semantics of well-defined feature. This feature was marked as"obsolescent" in C.

8.5.3功能说:

4. The parameter-declaration-clause determines the arguments that can be specified, and their processing, when
the function is called. [...] If the parameter-declaration-clause is empty, the function
takes no arguments. The parameter list (void) is equivalent to the empty parameter list.

C99

正如C ++ 11所提到的,int f()没有指定参数,而且过时了。

它可以导致工作代码或UB。

我在以下网址详细解释了C99标准:https://stackoverflow.com/a/36292431/895245


在C中,在空函数引用中使用void,以便编译器具有原型,并且该原型具有"无参数"。在C ++中,您不必告诉编译器您有原型,因为您不能省略原型。


推荐阅读