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

前端 未结 4 514
情话喂你
情话喂你 2020-11-22 16:00

Consider these two function definitions:

void foo() { }

void foo(void) { }

Is there any difference between these two? If not, why is the <

4条回答
  •  余生分开走
    2020-11-22 16:45

    C++11 N3337 standard draft

    There is no difference.

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

    Annex C "Compatibility" C.1.7 Clause 8: declarators says:

    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:

    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 functions says:

    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

    As mentioned by C++11, int f() specifies nothing about the arguments, and is obsolescent.

    It can either lead to working code or UB.

    I have interpreted the C99 standard in detail at: https://stackoverflow.com/a/36292431/895245

提交回复
热议问题