Using void in functions without parameter?

前端 未结 5 976
说谎
说谎 2021-02-19 07:44

In C++ using void in a function with no parameter, for example:

class WinMessage
{
public:
    BOOL Translate(void);
};

is redunda

相关标签:
5条回答
  • 2021-02-19 08:35

    I feel like no. Reasons:

    • A lot more code out there has the BOOL Translate() form, so others reading your code will be more comfortable and productive with it.
    • Having less on the screen (especially something redundant like this) means less thinking for somebody reading your code.
    • Sometimes people, who didn't program in C in 1988, ask "What does foo(void) mean?"
    0 讨论(0)
  • 2021-02-19 08:37

    I think it will only help in backward compatibility with older C code, otherwise it is redundant.

    0 讨论(0)
  • 2021-02-19 08:39

    In C++

    void f(void);
    

    is identical to:

    void f();
    

    The fact that the first style can still be legally written can be attributed to C.
    n3290 § C.1.7 (C++ and ISO C compatibility) states:

    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
    

    In C, it makes sense to avoid that undesirable "unknown" meaning. In C++, it's superfluous.

    Short answer: in C++ it's a hangover from too much C programming. That puts it in the "don't do it unless you really have to" bracket for C++ in my view.

    0 讨论(0)
  • 2021-02-19 08:46

    Just as a side note. Another reason for not including the void is that software, like starUML, that can read code and generate class diagrams, read the void as a parameter. Even though this may be a flaw in the UML generating software, it is still annoying to have to go back and remove the "void"s if you want to have clean diagrams

    0 讨论(0)
  • 2021-02-19 08:48

    I see absolutely no reason for this. IDEs will just complete the function call with an empty argument list, and 4 characters less.

    Personally I believe this is making the already verbose C++ even more verbose. There's no version of the language I'm aware of that requires the use of void here.

    0 讨论(0)
提交回复
热议问题