Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting all void functions to non-void function

Tags:

c++

function

void

I think, it is better to return an integer even if the function does not actually return anything. The returned values can be used to reflect various error conditions inside the function. Is there any price we pay for by always opting an integer return function rather than a "void" function in C++?

like image 912
Soo Avatar asked May 18 '26 09:05

Soo


2 Answers

You'll have the computational overhead of having to return a value from every function. But a good optimiser might remove redundant return values.

It's bad idea as it will make your code unreadable. But it's a bad idea for another reason: it creates yet another possibility for undefined behaviour to creep into your program. Aside from main, all functions marked int must return an int on all control paths.

Why not use the exception mechanism; which is the idiomatic way?

like image 100
Bathsheba Avatar answered May 20 '26 23:05

Bathsheba


If you have a design policy that every function should return a code that tells you whether it succeeded, then changing void functions to return such a value makes sense. You end up passing output parameters by reference instead of returning values, and you get code that doesn't look like idiomatic C++. But if it's only functions that would otherwise return nothing, it's just an arbitrary change and will confuse people to no end.

If a function cannot do what it's supposed to do it should throw an exception.

like image 40
Pete Becker Avatar answered May 20 '26 21:05

Pete Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!