Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using void in functions without parameter?

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

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

is redundant, you might as well just write Translate();.

I, myself generally include it since it's a bit helpful when code-completion supporting IDEs display a void, since it ensures me that the function takes definitely no parameter.

My question is, Is adding void to parameter-less functions a good practice? Should it be encouraged in modern code?

like image 851
ApprenticeHacker Avatar asked Mar 03 '12 10:03

ApprenticeHacker


People also ask

Does a void function need a parameter?

When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal."

Can we define a function without the parameter?

Per the letter of the standard, yes Even though both T f() { ... } and T f(void) { ... } define a function with no parameters, these definitions are not 100% equivalent: the first form doesn't provide function prototype.

How do you call a function with no parameters?

C static code analysis: Functions without parameters should be declared with parameter type "void"

What happens when you create a function without any parameters?

(1) The variable side is not given to the parameter, but directly accessed by the function which is possible in JavaScript. (2) The function does not return any value but prints the output to the browser console.


1 Answers

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.

like image 169
Flexo Avatar answered Sep 30 '22 11:09

Flexo