Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell that there is no result of a function with return value?

I have a short question. Given a function which returns an object of a class as result, what should I return if there is no result (say because an index is out of range)? I could return a new "empty" object but how can I point out that there was no successful calculation?

I suppose there is a common approach.

like image 917
danijar Avatar asked Mar 05 '13 10:03

danijar


People also ask

How do you know when a function returns undefined?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

Which function has no return value?

Void (NonValue-Returning) functions: Void functions are created and used just like value-returning functions except they do not return a value after the function executes.

How do you check if a function returns a value?

To check if a function returns true , call the function and check if its return value is equal to true , e.g. if (func() === true) . If the function's return value is equal to true the condition will be satisfied and the if block will run.

What is the meaning of no return value?

Function with no argument and no return value: When a function has no arguments, it does not receive any data from the calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function.


1 Answers

The common approach in C++ is either to throw an exception or to use some wrapper like boost::optional.

An exception should be thrown if it is some kind of error, the boost::optional-approach is more appropriate if it is a valid use-case of your function to return an empty result. One example that comes to mind is SQL's NULL. boost::optional turned out quite handy in our codebase.

like image 179
Daniel Frey Avatar answered Sep 19 '22 09:09

Daniel Frey