Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is preferred: foo(void) or foo() in C++

Tags:

c++

void

I have seen two styles of defining conversion operator overload in C++,

  1. operator int* (void) const
  2. operator int*() const

Question 1. I think the two styles (whether add void or not) have the same function, correct?
Question 2. Any preference which is better?

like image 515
George2 Avatar asked Nov 30 '22 20:11

George2


2 Answers

This doesn't just apply to conversion operators but to all functions in C++ that take no parameters. Personally, I prefer to omit void for consistency.

The practice originates from C. Originally, when C did not have prototypes, an empty pair of braces was used in function declarations and did not provide any information about the parameters that the function expected.

When prototypes were added, empty braces were retained for function declarations to mean 'unspecified parameters' for flexibility and backwards compatibility. To provide an explicit prototype meaning 'takes no parameters', the syntax (void) was added.

In C++ all function declarations have to have prototypes, so () and (void) have the same meaning.

like image 84
CB Bailey Avatar answered Dec 08 '22 15:12

CB Bailey


Quoting from ISO C++ FAQ, Should I use f(void) or f()?

C programmers often use f(void) when declaring a function that takes no parameters, however in C++ that is considered bad style. In fact, the f(void) style has been called an "abomination" by Bjarne Stroustrup, the creator of C++, Dennis Ritchie, the co-creator of C, and Doug McIlroy, head of the research department where Unix was born.

If you're writing C++ code, you should use f(). The f(void) style is legal in C++, but only to make it easier to compile C code.

Appeal to authority FTW :)

like image 20
Merlyn Morgan-Graham Avatar answered Dec 08 '22 17:12

Merlyn Morgan-Graham