0

This is more of a philosophical/expirience question.

When functions, which return nothing of value, are written, should the default return value be void or int? Like, maybe returning int leaves place for adding error codes and error handling in the future? Is there even difference between two options in terms of performance and architecture?

Mivsher
  • 36
  • 3
  • 1
    In c++, you should either throw an exception or return an error object. No reason to return an int. – balki Mar 24 '20 at 23:15
  • Hi Mivsher, it looks like you are unhappy with a comment on your assignment. Would you mind providing more details? – Captain Giraffe Mar 24 '20 at 23:16

4 Answers4

1

Programming is engineering in a big part, and the principle of least surprise is one of the most useful engineering principles.

Hence, the least surprising thing to return for a function that returns nothing is void.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
1

In most cases, we have the option of changing the return type - or if not, then we can define a replacement function and possibly mark the old one deprecated. As such, there is rarely need to consider what you may want to return in future. So, choose the return type of the function based on what it does now. If it doesn't return an error code or anything else, then return void.

In the case you really have no option to change the return type later, you are in a situation where you have no room for experimentation. You must decide initially whether you should return an error code or not.

P.S. Integers are not an ideal form of error reporting. Consider something else such as exceptions, Boost.Outcome or at least std::error_code.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

It should be void. When a function has a return type, you are expecting to receive a value from that function(a value that you will use in your program). When a function is void, you are sure about the fact that your function return nothing and is doing some work(sorting an array for e.g.). What's the point in returning a value when is not needed?

Cipri
  • 69
  • 1
  • 8
0

You can take the Standards Committee's approach with the STL.

In ISO SD-8, it says they reserve the right to make compatible API changes, such as changing from void to something non-void. This change, in any case I can think of, is backwards compatible in every way.

Zuodian Hu
  • 979
  • 4
  • 9